httpClient工具類

md3c 9年前發布 | 3K 次閱讀 Java HttpClient

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();  
    }  
}  

} </pre>

 本文由用戶 md3c 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!