基於HttpClient實現Http訪問工具類
HttpClient官方下載地址:http://hc.apache.org/downloads.cgi
如果使用的是jar包方式,將下載的jar新增到專案中Build Path即可.
如果使用的是maven 新增pom.xml依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
HttpClientUtil.java:
package com.yrok.socket.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
*
* @author Nan 2015-11
*/
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm;
private static String EMPTY_STR = "";
private static String UTF_8 = "UTF-8";
private static void init() {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(50);// 整個連線池最大連線數
cm.setDefaultMaxPerRoute(5);// 每路由最大連線數,預設值是2
}
}
/**
* 通過連線池獲取HttpClient
*
* @return
*/
private static CloseableHttpClient getHttpClient() {
init();
return HttpClients.custom().setConnectionManager(cm).build();
}
/**
*
* @param url
* @return
*/
public static String httpGetRequest(String url) {
HttpGet httpGet = new HttpGet(url);
return getResult(httpGet);
}
public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
return getResult(httpGet);
}
public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws URISyntaxException {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return getResult(httpGet);
}
public static String httpPostRequest(String url) {
HttpPost httpPost = new HttpPost(url);
return getResult(httpPost);
}
public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
return getResult(httpPost);
}
public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
return getResult(httpPost);
}
private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
return pairs;
}
/**
* 處理Http請求
*
* @param request
* @return
*/
private static String getResult(HttpRequestBase request) {
// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = getHttpClient();
try {
CloseableHttpResponse response = httpClient.execute(request);
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
// long len = entity.getContentLength();// -1 表示長度未知
String result = EntityUtils.toString(entity);
response.close();
// httpClient.close();
return result;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return EMPTY_STR;
}
}
參考文件:http://blog.csdn.net/wangnan537/article/details/50374061
相關文章
- 關於golang http.HttpClient.Do的問題GolangHTTPclient
- 基於Docker的MongoDB實現授權訪問DockerMongoDB
- 《Linux-SVN實現http訪問》LinuxHTTP
- HttpClient請求工具類HTTPclient
- .net core基於HttpClient實現的網路請求庫HTTPclient
- Holer實現外網訪問本地Apache HTTP ServerApacheHTTPServer
- java實現Excel定製匯出(基於POI的工具類)JavaExcel
- 基於Yarp實現內網http穿透內網HTTP穿透
- 基於Pytorch實現貓狗分類PyTorch
- Nginx基於客戶端請求頭的訪問分類Nginx客戶端
- java http 工具類JavaHTTP
- c# 基類派生類成員方法訪問C#
- 基於資源的HTTP Cache的實現介紹HTTP
- kubernetes使用http rest api訪問叢集之使用postman工具訪問 apiserverHTTPRESTAPIPostmanServer
- 基於 JMeter的壓測工具的實現JMeter
- 基於PLM訪問控制模型研究模型
- 基於註解的 PHP 列舉類實現PHP
- 基於SWT的類XUL實現: SWT-XUIUI
- C++派生類物件訪問基類的protected成員C++物件
- Spring Security實現基於RBAC的許可權表示式動態訪問控制Spring
- 基於bootstrap實現視覺化佈局工具boot視覺化
- (視訊) 基於HTML5的伺服器遠端訪問工具HTML伺服器
- HTTP之訪問控制「CORS」HTTPCORS
- 為HttpClient開啟HTTP/2HTTPclient
- 域名訪問和ip訪問引起的http 403問題HTTP
- 基於Dubbo的http自動測試工具分享HTTP
- 基於.NetCore開發部落格專案 StarBlog - (11) 實現訪問統計NetCore
- Objective-C如何自己實現一個基於陣列下標的屬性訪問模式Object陣列模式
- tcp 實現簡單http 問題TCPHTTP
- 資料安全合規需要從基於角色的訪問控制邁向基於屬性的訪問控制
- Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸Spring BootRESTHTTPJSON
- 資料庫工具類實現資料庫
- .Net Core實戰之基於角色的訪問控制的設計
- grpc提供http訪問方式RPCHTTP
- 基於角色管理的系統訪問控制
- 使用httpclient傳送http請求HTTPclient
- 基於Tensorflow + Opencv 實現CNN自定義影像分類OpenCVCNN
- 一款基於語法的HTTP漏洞挖掘工具HTTP