当前位置: 首页 > news >正文

国产免费cad软件下载重庆官网seo分析

国产免费cad软件下载,重庆官网seo分析,网站开发流程 图书,旅游网站策划书SpringBoot调用外部接口的几种方式 使用FeignClient调用1、在使用方引入依赖2、服务接口调用方2.1、在启动类上加上EnableFeigncliens注解2.2、编写Feign接口调用服务controller层2.3、服务接口调用service层 3、服务接口提供者4、说明 使用RestTemplate调用1、引入依赖2、Rest…

SpringBoot调用外部接口的几种方式

  • 使用FeignClient调用
    • 1、在使用方引入依赖
    • 2、服务接口调用方
      • 2.1、在启动类上加上@EnableFeigncliens注解
      • 2.2、编写Feign接口调用服务controller层
      • 2.3、服务接口调用service层
    • 3、服务接口提供者
    • 4、说明
  • 使用RestTemplate调用
    • 1、引入依赖
    • 2、RestTemplateConfig配置类
    • 3、接口调用
  • 使用WebClient调用
    • 1、引入依赖
    • 2、接口调用示例
  • 使用Apache HttpClient调用
  • 使用HttpURLConnection调用
  • 使用OkHttp调用
    • 1、引入依赖
    • 2、示例代码
  • 使用AsyncHttpClient调用
    • 1、引入依赖
    • 2、示例代码

使用FeignClient调用

FeignClient调用大多用于微服务开发中,各服务之间的接口调用。它以Java接口注解的方式调用HTTP请求,使服务间的调用变得简单

1、在使用方引入依赖

<!-- Feign注解 这里openFeign的版本要和自己使用的SpringBoot匹配-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><!-- <version>4.0.1</version> -->
</dependency>

2、服务接口调用方

2.1、在启动类上加上@EnableFeigncliens注解


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableFeignClients
public class StudyfeignApplication {public static void main(String[] args) {SpringApplication.run(StudyfeignApplication.class, args);System.out.println("项目启动成功");}}

2.2、编写Feign接口调用服务controller层

import com.hysoft.studyfeign.service.SysUserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("feign")
public class SysUserController {@Autowiredprivate SysUserClient sysUserClient;@PostMapping("getUserId")public void getUserId(String userId){this.sysUserClient.getUserById(userId);}}

2.3、服务接口调用service层

feign的客户端需要使用@FeignClient注解进行表示,这样扫描时才知道这是一个feign客户端。@FeignClient最常用的就两个属性,一个name,用于给客户端定义一个唯一的名称,另一个就是url,用于定义该客户端调用的远程地址。url中的内容,可以写在配置文件application.yml中,便于管理
@Service
@FeignClient(name = "feign-service",url = "${master-getuserbyId}")
public interface SysUserClient {@PostMapping("/master/test")String getUserById(String id);}

application.yml中的配置如下

server:port: 8081
master-getuserbyId: http://localhost:8080

3、服务接口提供者

对于接口提供者来说没有特别要求,和正常的接口开发一样

4、说明

需要说明的是,在接口调用方,可以继续拓展service层,书写service实现层,进一步进行拓展	
import org.springframework.stereotype.Service;@Service
public class SysUserClientImpl implements SysUserClient{@Overridepublic String getUserById(String id) {return "";}
}

使用RestTemplate调用

RestTemplate中几个常用的方法:getForObject()、getForEntity()、postForObject()、postForEntity()。其中,getForObject() 和 getForEntity() 方法可以用来发送 GET 请求

1、引入依赖

  <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>

2、RestTemplateConfig配置类

SimpleClientHttpRequestFactory类对应的HTTP库是JDK自带的HttpUrlConnection,当然我们可以根据自身的需求使用其他的HTTP库,例如HttpComponentsAsyncClientHttpRequestFactory

@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory){return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory(){SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);//单位为msfactory.setConnectTimeout(5000);//单位为msreturn factory;}
}

3、接口调用


@RestController
public class TestRestTemplate {@Resourceprivate RestTemplate restTemplate;@GetMapping(value = "/saveUser")public void saveUser(String userId) {String url = "http://127.0.0.1:8080/master/test";Map map = new HashMap<>();map.put("userId", "hy001");String results = restTemplate.postForObject(url, map, String.class);}}

使用WebClient调用

Spring3.0引入了RestTemplate,但是在后来的官方源码中介绍,RestTemplate有可能在未来的版本中被弃用,所谓替代RestTemplate,在Spring5中引入了WebClient作为异步的非阻塞、响应式的HTTP客户端。

1、引入依赖


<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2、接口调用示例


public class TestWebClient {@Testpublic void doGet() {String userId = "郭郭";String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId={userId}";Mono<String> mono = WebClient//创建WebClient实例.create()//方法调用,WebClient中提供了多种方法.get()//请求url.uri(url, userId)//获取响应结果.retrieve()//将结果转换为指定类型.bodyToMono(String.class);//返回最终结果:block是阻塞的/subscribe()非阻塞式获取响应结果System.out.println("响应结果:" + mono.block());}@Testpublic void doPost() {Map map = new HashMap<>();map.put("name", "郭郭");String requestBody = JSON.toJSONString(map);String url = "http://127.0.0.1:8080/master/test/saveUser";Mono<String> mono = WebClient//创建WebClient实例.create()//方法调用,WebClient中提供了多种方法.post()//请求url.uri(url)//指定请求的Content-Type为JSON.contentType(MediaType.APPLICATION_JSON)//使用bodyValue方法传递请求体.bodyValue(requestBody)//获取响应结果.retrieve()//将结果转换为指定类型.bodyToMono(String.class);//返回最终结果:block是阻塞的/subscribe()非阻塞式获取响应结果System.out.println("响应结果:" + mono.block());}
}
在上述doPost请求中,我们的请求接口入参是一个Map,但是需要转换为JSON格式传递,这是因为WebClient默认是使用JSON序列化的。

使用Apache HttpClient调用


public class TestHttpClient {@Testpublic void doGet() throws IOException {//步骤一:创建httpClient实例CloseableHttpClient httpClient = HttpClients.createDefault();//步骤二:创建HTTP请求HttpGet httpGet = new HttpGet("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=郭郭");//步骤三:发送请求并获取响应数据CloseableHttpResponse response = httpClient.execute(httpGet);//步骤四:处理响应数据HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);//步骤五:关闭httpClient和responseresponse.close();httpClient.close();}@Testpublic void doPost() throws IOException {//步骤一:创建httpClient实例CloseableHttpClient httpClient = HttpClients.createDefault();//步骤二:创建HTTP请求HttpPost httpPost = new HttpPost("http://127.0.0.1:8094/masterdata/sysUser/saveUser");//步骤三:设置请求体数据,使用JSON格式Map map = new HashMap<>();map.put("name", "郭郭");String requestBody = JSON.toJSONString(map);StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);//步骤四:发送请求并获取响应数据CloseableHttpResponse response = httpClient.execute(httpPost);//步骤五:处理响应数据HttpEntity entity = response.getEntity();String result = EntityUtils.toString(entity);//步骤五:关闭httpClient和responseresponse.close();httpClient.close();}
}

使用HttpURLConnection调用


public class TestHttpURLConnection {@Testpublic void doGet() throws IOException {String userId = "郭郭";  // 参数值userId = URLEncoder.encode(userId, "UTF-8"); // 对参数值进行URL编码//步骤一:创建URL对象URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=" + userId);//步骤二:打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//步骤三:设置请求方式conn.setRequestMethod("GET");//步骤四:读取响应内容BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));StringBuilder sb = new StringBuilder();String line;while ((line = reader.readLine()) != null) {sb.append(line);}reader.close();System.out.println(sb.toString());} @Testpublic void doPost() throws IOException {//创建URL对象URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/saveUser");//打开连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置请求方式conn.setRequestMethod("POST");// 设置请求头conn.setRequestProperty("Content-Type", "application/json");//启用输出流conn.setDoOutput(true);//设置请求体数据Map map = new HashMap<>();map.put("name", "郭郭");String requestBody = JSON.toJSONString(map);//发送请求体数据try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) {outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));}//读取响应内容BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));StringBuilder sb = new StringBuilder();String line;while ((line = reader.readLine()) != null) {sb.append(line);}reader.close();System.out.println(sb.toString());} }

使用OkHttp调用

1、引入依赖


<!--okhttp依赖--><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.0.0</version></dependency>

2、示例代码


public class TestOkHttp {@Testpublic void doGet() throws IOException {OkHttpClient client = new OkHttpClient();String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId=郭郭";Request request = new Request.Builder().url(url).build();try (Response response = client.newCall(request).execute()) {ResponseBody body = response.body();System.out.println(body.string());}}@Testpublic void doPost() throws IOException{OkHttpClient client = new OkHttpClient();String url = "http://127.0.0.1:8080/master/test/saveUser";MediaType mediaType = MediaType.get("application/json; charset=utf-8");//requestBody请求入参Map map = new HashMap<>();map.put("name", "admin");RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(map));Request request = new Request.Builder().url(url).post(requestBody).build();try (Response response = client.newCall(request).execute()) {ResponseBody body = response.body();System.out.println(body.string());}}
}

使用AsyncHttpClient调用

1、引入依赖

<dependency><groupId>org.asynchttpclient</groupId><artifactId>async-http-client</artifactId><version>2.12.3</version>
</dependency>

2、示例代码

public class TestAsyncHttpClient {@Testpublic void doGet() throws IOException {try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {BoundRequestBuilder requestBuilder = client.prepareGet("http://127.0.0.1:8080/master/test/getSysUserById?userId=hy001");CompletableFuture<String> future = requestBuilder.execute().toCompletableFuture().thenApply(Response::getResponseBody);//使用join等待响应完成String responseBody = future.join();System.out.println(responseBody);}}@Testpublic void doPost() throws IOException {try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {BoundRequestBuilder requestBuilder = client.preparePost("http://127.0.0.1:8094/8080/master/test/saveUser");//requestBody请求入参Map map = new HashMap<>();map.put("name", "admin");String requestBody = JSON.toJSONString(map);requestBuilder.addHeader("Content-Type", "application/json");requestBuilder.setBody(requestBody);CompletableFuture<String> future = requestBuilder.execute().toCompletableFuture().thenApply(Response::getResponseBody);//使用join等待响应完成String responseBody = future.join();System.out.println(responseBody);}}}
http://www.yidumall.com/news/8339.html

相关文章:

  • 暗网网站有那些最近五天的新闻大事
  • 做网站app要多钱班级优化大师客服电话
  • 如何进行网站设计天津seo优化公司哪家好
  • 做网站的研究生专业运营主要做什么工作
  • 用网站开发客户发邮件百度官网认证入口
  • 下列关于网站开发中网页seo怎么做最佳
  • 建设机械网站资讯seo怎么刷关键词排名
  • html5 开发网站百度推广代理商返点
  • 网站编辑简历刚刚北京传来重大消息
  • 网站做担保交易平台阿里云域名注册官网
  • 郑州做网站的t和p在一起怎么做网站
  • 烟台哪个公司做网站好外贸独立站怎么做
  • 评价一个网站设计项目的好坏手机优化大师为什么扣钱
  • 什么网站建设比较好的百度推广关键词查询
  • 开发员给我用织梦做的网站星链seo管理
  • 浙江嘉兴最新事件seo管理软件
  • 加强县政府网站建设的几点建议网络推广深圳有效渠道
  • 网站负责人 法人站长之家seo查询官方网站
  • 网站手机客户端开发教程北京网站制作
  • 怎么在网站做外部链接整合营销方案怎么写
  • 亳州公司做网站央视新闻
  • 网站建设公司在哪里百度收录api怎么提交
  • 西宁做网站制作的公司公司品牌宣传
  • 免费网站商城建设什么是搜索引擎销售
  • 古镇企业网站建设网络安全培训最强的机构
  • 织梦网站怎么做优化前端开发
  • 成都市城乡建设委员会的网站在线的crm系统软件
  • 网站设计师与网站开发工程师百度框架户开户渠道代理
  • 织梦中英文版网站怎么做sem代运营费用
  • 商业网站开发深圳最好seo