通过http-WebClient、HttpClient调用其它服务接口,区别,提供两个简单demo演示

目录

 

一、WebClient和HttpClient说明

二、WebClient概念

三、HttpClient概念

四、HttpClient的简单使用--只说明json参数的情况

五、WebClient的简单使用--只说明json参数的情况


一、WebClient和HttpClient说明

  • WebClient在SpringBoot是有启动器的,HttpClient没有启动器,需要自己去配置
  • WebClent简单,HttpClient功能更强大,看需选择,HttpClient用的人相对会比较多

使用场景:当我需要一个第三方接口返回数据时,我们不通过网关或者oapi等其它方式去调用,而是直接本地调其它服务的方式获取返回数据,此时用到这两个类了。其实就连SpringCloud中服务和服务之间的调用全部是使用HttpClient

二、WebClient概念

WebClient是从Spring WebFlux 5.0版本开始提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具。它的响应式编程的基于Reactor的。WebClient中提供了标准Http请求方式对应的get、post、put、delete等方法,可以用来发起相应的请求。下面的代码是一个简单的WebClient请求示例,调用百度,整个代码解释、过程如下:

  1. WebClient.create()创建一个WebClient的实例
  2. 可以通过get()post()等选择调用方式
  3. uri()指定需要请求的路径
  4. retrieve()用来发起请求并获得响应
  5. bodyToMono(String.class)用来指定请求结果需要处理为String,并包装为Reactor的Mono对象。
WebClient webClient = WebClient.create();
Mono<String> mono = webClient.get().uri("https://www.baidu.com").retrieve().bodyToMono(String.class);
mono.subscribe(System.out::println);

三、HttpClient概念

HttpClient是客户端的http通信实现库,这个类库的作用是接收和发送http报文,使用这个类库,它相比传统的 HttpURLConnection,增加了易用性和灵活性,我们对于http的操作会变得简单一些;SpringCloud中服务和服务之间的调用全部是使用HttpClient,可见HttpClient的强大

HttpClient功能比较强大,这里不做太多解释,直接demo展示,后面一篇文章会专门去配置SpringBoot的HttpClient,提供多个api直接调用即可。

四、HttpClient的简单使用--只说明json参数的情况

1、引入依赖

		<!-- 引入HttpClient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.10</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.6</version>
		</dependency>

2、提供一个其它服务的接口,如下(例子参数复杂-接口,自己可以换个简单的)

已经知道的服务启动的ip是:192.124.1.99:8830,请求接口:/cust/maintainPersonAddr/getNonStandardPersonAddr

所以其它服务接口地址url:http://192.124.1.99:8830/cust/maintainPersonAddr/getNonStandardPersonAddr

3、demo调用

public class WebClientTest {
    private final static String host = "http://192.124.1.99:8830";
    private final static String path = "/cust/maintainPersonAddr/getNonStandardPersonAddr";

    /**
     * 通过HttpClient调用它方接口
     *
     * @return 返回响应结果
     */
    public static GenericDTO<GetNonStandardPersonAddrRspDTO> synHttpClientToOther(GenericDTO<GetPersonAddrReqDTO> reqDto) {
        //创建HttpClient对象
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
            //设置请求路径,请求格式
            HttpPost httpPost = new HttpPost(host + path);
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

            //格式化请求数据并设值
            String parameter = JsonUtils.toJSON(reqDto);
            StringEntity se = new StringEntity(parameter);
            se.setContentType("text/json");
            httpPost.setEntity(se);

            //设置超时,连接超时:setConnectTimeout;传输超时:setSocketTimeout
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setSocketTimeout(10000).build();
            httpPost.setConfig(requestConfig);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                //返回信息
                if (response.getStatusLine().getStatusCode() == 200) {
                    String results = EntityUtils.toString(response.getEntity(), "UTF-8");
                    //转成对象
                    GenericDTO rspDto = JsonUtils.toBean(results, GenericDTO.class);
                    rspDto.setBody(JsonUtils.toBean(rspDto.getBody(), GetNonStandardPersonAddrRspDTO.class));
                    return rspDto;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Test
    public void getToByWebClientFromOtherTest() {
        GenericDTO<GetPersonAddrReqDTO> reqDto = new GenericDTO<>();
        GetPersonAddrReqDTO getDto = new GetPersonAddrReqDTO();
        getDto.setCiNo("50000032");
        getDto.setAddrNo(1);
        reqDto.setBody(getDto);

        //HttpClient调用
        GenericDTO<GetNonStandardPersonAddrRspDTO> rspDto = synHttpClientToOther(reqDto);
        System.out.println(rspDto);

    }
}

大概分为5步,感觉没啥好解释的——

五、WebClient的简单使用--只说明json参数的情况

1、引入依赖

		<!-- 引入WebClient -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webflux</artifactId>
		</dependency>

2、提供一个其它服务的接口,如下(例子参数复杂-接口,自己可以换个简单的)

已经知道的服务启动的ip是:192.124.1.99:8830,请求接口:/cust/maintainPersonAddr/getNonStandardPersonAddr

所以其它服务接口地址url:http://192.124.1.99:8830/cust/maintainPersonAddr/getNonStandardPersonAddr

3、demo调用

public class WebClientTest {
    private final static String host = "http://192.124.1.99:8830";
    private final static String path = "/cust/maintainPersonAddr/getNonStandardPersonAddr";

    /**
     * 通过WebClient调用它方接口
     *
     * @param reqDto
     * @return
     */
    public static GenericDTO<GetNonStandardPersonAddrRspDTO> getToByWebClientFromOther(GenericDTO<GetPersonAddrReqDTO> reqDto) {
        Mono<String> mono = null;
        //将请求参数转成json,网上随便找个转换工具
        String reqDtos = JsonUtils.toJSON(reqDto);
        //post请求调用第三方接口
        mono = WebClient.create().post().uri(host + path)
                //指定为JSON参数
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(reqDtos)
                //获取响应体
                .retrieve()
                //响应数据类型转换
                .bodyToMono(String.class);

        //格式化响应信息
        String response = mono.block();
        GenericDTO rspDto = JsonUtils.toBean(response, GenericDTO.class);
        rspDto.setBody(JsonUtils.toBean(rspDto.getBody(), GetNonStandardPersonAddrRspDTO.class));
        return rspDto;
    }

    @Test
    public void getToByWebClientFromOtherTest() {
        GenericDTO<GetPersonAddrReqDTO> reqDto = new GenericDTO<>();
        GetPersonAddrReqDTO getDto = new GetPersonAddrReqDTO();
        getDto.setCiNo("50000032");
        getDto.setAddrNo(1);
        reqDto.setBody(getDto);

        //WebClient调用
        GenericDTO<GetNonStandardPersonAddrRspDTO> rspDto = getToByWebClientFromOther(reqDto);
        System.out.println(rspDto.getBody().toString());

    }
}

其实主要内容分为处理请求数据、调用请求接口、处理响应数据。这里的处理请求数据和处理响应数据可以去掉,我在另外一个HttpClient的文章中封装的接口是直接传入JSON数据,传出String,格式处理不在方法里面。

猜你喜欢

转载自blog.csdn.net/qq_41055045/article/details/108472571
今日推荐