首页 > 技术文章 > SpringBoot使用HttpClient远程调用

nlbz 2021-04-27 11:11 原文

HttpClient的使用

一、介绍
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。

二、使用方法

1、添加依赖

引入httpClient依赖
<!-- http通信 -->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.4</version>
</dependency>
引入fastjson依赖
<!-- 解析json -->
<dependency>
	<groupId>com.alibaba</groupId>
	<version>1.2.62</version>
</dependency>

2、 编写代码

​ 1、创建HttpClient对象。(推荐用CloseableHttpClient,HttpClient是历史遗留版本,官方推荐使用CloseableHttpClient)

注:两者的依赖不同

  2、创建请求方法的实例,并指定请求uri。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

  3、如果需要发送请求参数,直接在请求地址后拼接参数(√);对于HttpPost对象而言,也可先设置参数队列,然后调用setEntity(HttpEntity entity)方法来设置请求参数。

  4、调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse/CloseableHttpResponse。

  5、调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,如果出现乱码,可以将HttpEntity对象改成StringEntity,可通过该对象获取服务器的响应内容。

  6、释放连接,无论方法是否执行成功,都应当必须释放

@RequestMapping("/Crawling")
public String test() {
    String file = wxCrawling.getFileurl();
    UploadDto upload = useupdateService.gzhwebcontent(file);
    //创建httpClient对象
    CloseableHttpClient client = HttpClients.createDefault();
    //将实体对象转化为json格式对象
    String uploadDto = JSON.toJSONString(upload);
    //编写访问地址
    String url = "http://192.168.18.109:9096//v1/wechat/upload";
    //创建HttpPost请求
    HttpPost post = new HttpPost(url);
    try {
        StringEntity stringEntity = new StringEntity(uploadDto, Charset.forName("UTF-8"));
        //设置请求参数
        post.setEntity(stringEntity);
        //调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse/CloseableHttpResponse。
        HttpResponse execute = client.execute(post);
        System.out.println(execute);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;

推荐阅读