httpClient工具類,httpclient

來源:互聯網
上載者:User

httpClient工具類,httpclient

package com.chinatelecom.personalcustom.common.util;import com.chinatelecom.personalcustom.PersonalCustomConst;import com.chinatelecom.personalcustom.model.WapLogBean;import com.fasterxml.jackson.databind.ObjectMapper;import com.ning.http.client.AsyncHttpClient;import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;import com.ning.http.client.AsyncHttpClientConfig;import com.ning.http.client.providers.netty.NettyResponse;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.StringRequestEntity;import org.apache.commons.httpclient.params.HttpConnectionManagerParams;import org.apache.commons.httpclient.params.HttpMethodParams;import org.jboss.netty.handler.codec.http.HttpHeaders;import java.net.URLEncoder;import java.util.Map;import java.util.Map.Entry;import java.util.Set;public class HttpUtil {/** * 請求逾時時間 */private static final int SO_TIMEOUT = 45000;/** * 請求失敗時重試次數 */private static final int RETRY_COUNT = 5;/** * 最大允許串連數 */private static final int MAX_TOTAL_CONNECTION = 200;/** * 非同步請求對象 */private static AsyncHttpClient asyncHttpClient;private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();static {HttpConnectionManagerParams params = new HttpConnectionManagerParams();params.setMaxTotalConnections(MAX_TOTAL_CONNECTION);connectionManager.setParams(params);}/** * 設定非同步請求參數 */static {AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();builder.setMaximumConnectionsTotal(300);builder.setMaximumConnectionsPerHost(90);        builder.setRequestTimeoutInMs(SO_TIMEOUT);asyncHttpClient = new AsyncHttpClient(builder.build());}/** * 擷取同步請求串連 */private static HttpClient getHttpClientInstance() {HttpClient client = new HttpClient(connectionManager);        client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(RETRY_COUNT, true));        client.getParams().setSoTimeout(SO_TIMEOUT);return client;}/** * POST請求 */public static HttpResponse post(String url, Map<String,Object> params) throws Exception {HttpResponse response = new HttpResponse();HttpClient client = getHttpClientInstance();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader(HttpHeaders.Names.USER_AGENT, PersonalCustomConst.USER_AGENT);postMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");ObjectMapper mapper = new ObjectMapper();try {StringRequestEntity stringRequestEntity = new StringRequestEntity(mapper.writeValueAsString(params));postMethod.setRequestEntity(stringRequestEntity);int returnCode = client.executeMethod(postMethod);response.setStatusCode(returnCode);response.setBody(postMethod.getResponseBodyAsString());} finally {postMethod.releaseConnection();}return response;}/** * POST請求 */public static HttpResponse post(String url, String params) throws Exception {HttpResponse response = new HttpResponse();HttpClient client = getHttpClientInstance();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader(HttpHeaders.Names.USER_AGENT, PersonalCustomConst.USER_AGENT);postMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");try {StringRequestEntity stringRequestEntity = new StringRequestEntity(params);postMethod.setRequestEntity(stringRequestEntity);int returnCode = client.executeMethod(postMethod);response.setStatusCode(returnCode);response.setBody(postMethod.getResponseBodyAsString());} finally {postMethod.releaseConnection();}return response;}/** * GET請求 */public static HttpResponse get(String url, Map<String,String> params) throws Exception {HttpResponse response = new HttpResponse();HttpClient client = getHttpClientInstance();GetMethod getMethod = null;try {StringBuffer buffer = new StringBuffer();buffer.append(url).append("?t=").append(System.currentTimeMillis());        Set<Entry<String, String>> entries = params.entrySet();        for (Entry<String, String> entry : entries) {            if (entry != null && entry.getValue() != null) {            buffer.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"UTF-8"));            }        }        getMethod = new GetMethod(buffer.toString());        getMethod.setRequestHeader(HttpHeaders.Names.CONTENT_TYPE, "UTF-8");        getMethod.getParams().setContentCharset("UTF-8");  int returnCode = client.executeMethod(getMethod);response.setStatusCode(returnCode);response.setBody(getMethod.getResponseBodyAsString());} finally {if(getMethod != null){getMethod.releaseConnection();}}return response;}/** * 非同步get請求 */public static HttpResponse aysnGet(String url,Map<String, Object> params,WapLogBean wapLogBean) throws Exception {HttpResponse response = new HttpResponse();try {StringBuffer buffer = new StringBuffer();buffer.append(url);if(params != null && params.size() > 0){buffer.append("?t=").append(System.currentTimeMillis());Set<Entry<String, Object>> entries = params.entrySet();        for (Entry<String, Object> entry : entries) {            if (entry != null && entry.getValue() != null) {            buffer.append("&").append(entry.getKey()).append("=").append(entry.getValue());            }        }}wapLogBean.setServerUrl(buffer.toString());        BoundRequestBuilder builder = asyncHttpClient.prepareGet(buffer.toString());        builder = builder.addHeader(HttpHeaders.Names.USER_AGENT,PersonalCustomConst.USER_AGENT);        NettyResponse nettyResponse = (NettyResponse) builder.execute().get();response.setStatusCode(nettyResponse.getStatusCode());response.setBody(nettyResponse.getResponseBody());} catch (Exception e) {throw e;}return response;}/** * 非同步post請求 */public static HttpResponse aysnPost(String url,Map<String, Object> params, String userAgent)throws Exception {HttpResponse response = new HttpResponse();try {        BoundRequestBuilder builder = asyncHttpClient.preparePost(url);        builder = builder.addHeader(HttpHeaders.Names.USER_AGENT,userAgent);        if(params != null && params.size() > 0){            builder = builder.setBody(JsonUtil.entityToJson(params));        }        NettyResponse nettyResponse = (NettyResponse) builder.execute().get();response.setStatusCode(nettyResponse.getStatusCode());response.setBody(nettyResponse.getResponseBody());} catch (Exception e) {throw e;}return response;}/** * 發送HTTP請求 */@SuppressWarnings("deprecation")public static String post(String url,String body, String userAgent, String contentType) throws Exception {String result = null;HttpClient client = getHttpClientInstance();PostMethod method = new PostMethod(url);method.addRequestHeader("User-Agent", userAgent);method.setRequestHeader("Content-Type", contentType);method.setRequestBody(body);try {client.executeMethod(method);result = method.getResponseBodyAsString();} finally {method.releaseConnection();}return result;}public static void destroy() {        if(asyncHttpClient != null){            asyncHttpClient.close();        }}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.