java模擬HTTP請求,傳送JSON資料
阿新 • • 發佈:2019-01-09
private static String DEFAULT_CHARSET = "utf-8";
/** 連線超時時間,由bean factory設定,預設為8秒鐘 */
private int defaultConnectionTimeout = 8000;
/** 迴應超時時間, 由bean factory設定,預設為60秒鐘 */
private int defaultSoTimeout = 2 * 60000;
/** 閒置連線超時時間, 由bean factory設定,預設為60秒鐘 */
private int defaultIdleConnTimeout = 60000;
private int defaultMaxConnPerHost = 30;
private int defaultMaxTotalConn = 80;
/** 預設等待HttpConnectionManager返回連線超時(只有在達到最大連線數時起作用):1秒 */
private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
/**
* HTTP連線管理器,該連線管理器必須是執行緒安全的.
*/
private HttpConnectionManager connectionManager;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
/**
* 工廠方法
*
* @return
*/
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}
/**
* 私有的構造方法
*/
private HttpProtocolHandler() {
// 建立一個執行緒安全的HTTP連線池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(
defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(
defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}
/**
* 執行Http請求
*
* @param request
* @return
*/
public HttpResponse execute(HttpRequest request) {
HttpClient httpclient = new HttpClient(connectionManager);
// 設定連線超時
int connectionTimeout = defaultConnectionTimeout;
if (request.getConnectionTimeout() > 0) {
connectionTimeout = request.getConnectionTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setConnectionTimeout(connectionTimeout);
// 設定迴應超時
int soTimeout = defaultSoTimeout;
if (request.getTimeout() > 0) {
soTimeout = request.getTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setSoTimeout(soTimeout);
// 設定等待ConnectionManager釋放connection的時間
httpclient.getParams().setConnectionManagerTimeout(
defaultHttpConnectionManagerTimeout);
String charset = request.getCharset();
charset = charset == null ? DEFAULT_CHARSET : charset;
HttpMethod method = null;
if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
method = new GetMethod(request.getUrl());
method.getParams().setCredentialCharset(charset);
// parseNotifyConfig會保證使用GET方法時,request一定使用QueryString
method.setQueryString(request.getQueryString());
} else {
method = new PostMethod(request.getUrl());
((PostMethod) method).addParameters(request.getParameters());
method.addRequestHeader("Content-Type",
"application/x-www-form-urlencoded; text/html; charset="
+ charset);
}
// 設定Http Header中的User-Agent屬性
method.addRequestHeader("User-Agent", "Mozilla/4.0");
HttpResponse response = new HttpResponse();
try {
httpclient.executeMethod(method);
if (request.getResultType().equals(HttpResultType.STRING)) {
response.setStringResult(method.getResponseBodyAsString());
} else if (request.getResultType().equals(HttpResultType.BYTES)) {
response.setByteResult(method.getResponseBody());
}
response.setResponseHeaders(method.getResponseHeaders());
} catch (UnknownHostException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (Exception ex) {
return null;
} finally {
method.releaseConnection();
}
return response;
}
/** 連線超時時間,由bean factory設定,預設為8秒鐘 */
private int defaultConnectionTimeout = 8000;
/** 迴應超時時間, 由bean factory設定,預設為60秒鐘 */
private int defaultSoTimeout = 2 * 60000;
/** 閒置連線超時時間, 由bean factory設定,預設為60秒鐘 */
private int defaultIdleConnTimeout = 60000;
private int defaultMaxConnPerHost = 30;
private int defaultMaxTotalConn = 80;
/** 預設等待HttpConnectionManager返回連線超時(只有在達到最大連線數時起作用):1秒 */
private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
/**
* HTTP連線管理器,該連線管理器必須是執行緒安全的.
*/
private HttpConnectionManager connectionManager;
private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
/**
* 工廠方法
*
* @return
*/
public static HttpProtocolHandler getInstance() {
return httpProtocolHandler;
}
/**
* 私有的構造方法
*/
private HttpProtocolHandler() {
// 建立一個執行緒安全的HTTP連線池
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(
defaultMaxConnPerHost);
connectionManager.getParams().setMaxTotalConnections(
defaultMaxTotalConn);
IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();
ict.addConnectionManager(connectionManager);
ict.setConnectionTimeout(defaultIdleConnTimeout);
ict.start();
}
/**
* 執行Http請求
*
* @param request
* @return
*/
public HttpResponse execute(HttpRequest request) {
HttpClient httpclient = new HttpClient(connectionManager);
// 設定連線超時
int connectionTimeout = defaultConnectionTimeout;
if (request.getConnectionTimeout() > 0) {
connectionTimeout = request.getConnectionTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setConnectionTimeout(connectionTimeout);
// 設定迴應超時
int soTimeout = defaultSoTimeout;
if (request.getTimeout() > 0) {
soTimeout = request.getTimeout();
}
httpclient.getHttpConnectionManager().getParams()
.setSoTimeout(soTimeout);
// 設定等待ConnectionManager釋放connection的時間
httpclient.getParams().setConnectionManagerTimeout(
defaultHttpConnectionManagerTimeout);
String charset = request.getCharset();
charset = charset == null ? DEFAULT_CHARSET : charset;
HttpMethod method = null;
if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
method = new GetMethod(request.getUrl());
method.getParams().setCredentialCharset(charset);
// parseNotifyConfig會保證使用GET方法時,request一定使用QueryString
method.setQueryString(request.getQueryString());
} else {
method = new PostMethod(request.getUrl());
((PostMethod) method).addParameters(request.getParameters());
method.addRequestHeader("Content-Type",
"application/x-www-form-urlencoded; text/html; charset="
+ charset);
}
// 設定Http Header中的User-Agent屬性
method.addRequestHeader("User-Agent", "Mozilla/4.0");
HttpResponse response = new HttpResponse();
try {
httpclient.executeMethod(method);
if (request.getResultType().equals(HttpResultType.STRING)) {
response.setStringResult(method.getResponseBodyAsString());
} else if (request.getResultType().equals(HttpResultType.BYTES)) {
response.setByteResult(method.getResponseBody());
}
response.setResponseHeaders(method.getResponseHeaders());
} catch (UnknownHostException ex) {
return null;
} catch (IOException ex) {
return null;
} catch (Exception ex) {
return null;
} finally {
method.releaseConnection();
}
return response;
}