使用 CloseableHttpClient 发送 get 请求调用其它的服务

导入依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

上代码

public class TestServiceImpl implements TestService {
//    @Resource
//    private CloseableHttpClient httpClient; // 这样可能注入不成功
    @Override
    public Object test() throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 构建一个 CloseableHttpClient 对象
        HttpGet get = new HttpGet("http://localhost:8280/jx/integral/order/list"); // 可以是 post 请求
    /**
     * 如果是 Post 请求
     * String jsonParams = gson.toJson(paramsMap); // 将请求参数转换成 JSON 字符串, paramsMap 是一个 Map,里面放的是请求参数
     * StringEntity entity = new StringEntity(jsonParams, "utf-8"); // 将其放入 StringEntity 中
     * entity.setContentType("application/json"); // 设置内容类型
     * httpPost.setEntity(entity); // 将 实体 放入到 HttpPost 当中
     * httpPost.setHeader("Accept", "application/json"); // 设置请求头
    */
        get.setHeader("Accept", "application/json");
        CloseableHttpResponse response = null;
        String string = null;
        try {
            response = httpClient.execute(get); // 执行 http 请求
            string = EntityUtils.toString(response.getEntity()); // 使用实体工具提取响应的实体
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            response.close(); // 记得关流
            return string;
        }
    }
}

参考: https://www.jianshu.com/p/9e69387f60f4

posted @ 2022-07-18 17:56  村上春树的叶子  阅读(253)  评论(0编辑  收藏  举报