最近项目中需要调用第三方平台的rest API,需要用到httpClient来发送http请求。简单封装了一个工具类。
下来具体说一下httpClient的使用首先得需要依赖 httpcore-4.4.3.jar和httpclient-4.5.1.jar,如果需要发送异步请求还需要httpasyncclient-4.1.1.jar和httpcore-nio-4.4.4.jar获取方法网上有很多 官方现在地址http://hc.apache.org/downloads.cgi,我使用的httpclient-4.5.1.jar。
1.使用httpclient 发送Get和Post请求
//get 请求
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("http://www.baidu.com");
System.out.println("Executing get request " + httpGet.getURI());
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine()); //返回请求的响应码
httpGet.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
//Post 请求
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(new BasicNameValuePair("参数名","参数值"));
System.out.println("Executing get request " + httpPost.getURI());
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine()); //返回请求的响应码
httpPost.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}