项目中经常需要调用别人系统的接口,无法使用dubbo等远程连接技术,这里使用httpClient直接在代码中发送请求。
依赖的jar
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<scope>compile</scope>
</dependency>
基本使用方式:
1:发送Post请求
//创建httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//用于接收返回数据
CloseableHttpResponse response = null;
try {
//创建post请求, url 最好trim(),避免出现空格导致发送失败
HttpPost httpPost = new HttpPost(url.trim());
//构造请求体(参数),一般将请求参数全部转为StringEntity 类型对象,同时设置请求头为json
httpPost.addHeader("Content-Type","application/json;UTF-8");
StringEntity entity = new StringEntity(param.toString(),"UTF-8");
httpPost .setEntity(entity);
//发送请求,(同步阻塞)
response = httpClient.execute(httpPost);
//将返回数据中的 Entity取出,转为字符串(此处可以 判断 response.getStatusLine().getStatusCode() == 200 判断是否返回成功)
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//将字符串转为json对象
JSONObject json = JSONObject.fromObject(result);
}catch(Exception e){
}finally{
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}