一、简介

HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。

HttpClient 是一个HTTP通信库、一个工具包,它只提供一个通用浏览器应用程序所期望的功能子集,与浏览器相比是没有界面的。

二、引入依赖

<!--httpclient-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.14</version>
</dependency>
<!--fastjson-->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.83</version>
</dependency>
<!--lombok-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>

三、创建测试实体

我们创建一个实体类用来接收HttpClient请求获取到的数据

package com.example.websocketdemo.bean;

import lombok.Data;

/**
 * @author qx
 * @date 2023/09/03
 * @desc 地址实体类
 */
@Data
public class Address {

    private String status;
    private String info;
    private String infocode;
    private String province;
    private String city;
    private String adcode;
    private String rectangle;

}

四、GET请求


    @Test
    void testGet() throws IOException {
        // 请求地址
        String url = "https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip=182.91.200.188";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 执行get请求
        CloseableHttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            // 解析Json数据
            Address address = JSONObject.parseObject(json, Address.class);
            System.out.println(address);
        }
    }

执行测试方法后控制台输出:

Address(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=桂林市, adcode=450300, rectangle=110.1648474,25.1596868;110.4296887,25.39682984)

五、POST请求

@Test
    void testPost() throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        String url = "https://restapi.amap.com/v3/ip";
        HttpPost httpPost = new HttpPost(url);
        // 设置请求参数
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));
        pairList.add(new BasicNameValuePair("ip", "182.91.200.188"));
        httpPost.setEntity(new UrlEncodedFormEntity(pairList));

        CloseableHttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            Address address = JSONObject.parseObject(json, Address.class);
            System.out.println(address);
        }
    }

执行测试方法后控制台输出:

Address(status=1, info=OK, infocode=10000, province=广西壮族自治区, city=桂林市, adcode=450300, rectangle=110.1648474,25.1596868;110.4296887,25.39682984)

六、注意事项

为防止请求数据乱码,我们可以主动设置编码。

 String json = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

七、发送文件

引入依赖:

 <!--如果需要灵活的传输文件,引入此依赖后会更加方便-->
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.5</version>
</dependency>

测试:

我们先创建一个用于文件上传的请求方法

package com.example.websocketdemo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author qx
 * @date 2023/09/03
 * @desc 文件上传控制器
 */
@RestController
public class FileController {

    @PostMapping("/upload")
    public String testFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件不存在";
        }
        // 图片保存地址
        String path = "D:" + File.separator + "test.jpg";
        file.transferTo(new File(path));
        return "保存成功";
    }
}

然后我们在单元测试类中添加上传文件的操作。

@Test
    void testFile() throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        // 图片上传请求地址
        HttpPost httpPost = new HttpPost("http://localhost:8081/upload");
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        String fileKey = "file";
        // 图片源路径
        File file = new File("C:/Users/Administrator/Desktop/0017029587773424_b.jpg");
        multipartEntityBuilder.addBinaryBody(fileKey, file);
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);

        CloseableHttpResponse response = client.execute(httpPost);
        if (response.getEntity() != null) {
            String responseStr = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println(responseStr);
        }
    }

启动程序和执行单元测试方法后,我们在控制台看到了控制器返回的数据。

保存成功

我们也在目的地址发现了我们新增的图片。

HttpClient在SpringBoot中的使用_GET