做项目避免不了调用第三方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进行了封装使得调用更加简单)