httpClient工具類

分類:IT技術 時間:2017-09-17
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 &amp;&amp; entry.getValue() != null) {  
                    buffer.append("&amp;").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 &amp;&amp; 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 &amp;&amp; entry.getValue() != null) {  
                        buffer.append("&amp;").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 &amp;&amp; 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();  
        }  
    }  
}  

Tags: import httpclient commons apache com org

文章來源:


ads
ads

相關文章
ads

相關文章

ad