使用httpclient调用第三方接口

做项目避免不了调用第三方api,httpclient就是可以进行交互。

1, 导入依赖

       //处理json数据
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
          

         //远程调用包
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.14</version>
        </dependency>

2,httpclient-get的调用

  @GetMapping("/b")
    public String TestGet() throws IOException {
        //1.声明出调用的客户端,相当于打开浏览器
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //2.声明返回的类型以及访问请求
        HttpGet httpGet = new HttpGet("http://localhost:8080/b/test");
        //3.执行请求
       CloseableHttpResponse response =  client.execute(httpGet);

       client.close();
       response.close();
       //4.获取返回内容
        return EntityUtils.toString(response.getEntity());

    }

3,httpclient-get的调用

 @PostMapping("/a")
    public String testA(com.jiang.pojo.TestA testA) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://43.155.113.91:9901/keywordSearchjw/getcontent");
        String json = JSONObject.toJSONString(testA);
        StringEntity stringEntity = null;
        try {
            stringEntity = new StringEntity(json);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-Type","application/json");

        CloseableHttpResponse response = null;

        response = client.execute(httpPost);
        client.close();
        response.close();
        return EntityUtils.toString(response.getEntity());

    }

下期发RestTemplate进行第三方接口调用(实际就是基于httpclient进行了封装使得调用更加简单)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值