HttpClient

Posted 明湖樵夫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient相关的知识,希望对你有一定的参考价值。

package com.tomtop.script.uc;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**

 *
 * @since 2013-12-18
 */
public class HttpClientUtil {

    //private static final Log log = LogFactory.getLog(SendMessageUtil.class);
    
    private static final String CHARSET = "GBK";
    private static final int TIMEOUT=5*1000*60;
    private static final int CONNECTION_TIMEOUT=5*1000*60;
    private static final int SO_TIMEOUT=5*1000*60;
    
    private HttpClientUtil(){}
    
    private static HttpClient httpClient ;
    
    @SuppressWarnings("deprecation")
    private static synchronized HttpClient getHttpClient(){
        if(null == httpClient){
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter("http.method.retry-handler", new DefaultHttpRequestRetryHandler());
            httpParams.setBooleanParameter("http.connection.stalecheck", false);
            HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParams, CHARSET);
            HttpProtocolParams.setUseExpectContinue(httpParams, true);
            ConnManagerParams.setTimeout(httpParams, TIMEOUT);
            HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
            
            SchemeRegistry schemeReg = new SchemeRegistry();
            schemeReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            ClientConnectionManager conManager = new ThreadSafeClientConnManager(httpParams, schemeReg);
            httpClient = new DefaultHttpClient(conManager,httpParams);
        }
        return httpClient;
    }

    public static String sendHttpMessage(String url,Map<String, String> map) throws Exception{
        try {
            if(StringUtil.isEmpty(url) || null == map || map.isEmpty()){
                return null;
            }
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-type", (new StringBuilder()).append("application/x-www-form-urlencoded; charset=").append(CHARSET).toString());
            post.setHeader("Accept",new StringBuffer("text/xml;charset=").append(CHARSET).toString());
            post.setHeader("Cache-Control", "no-cache");
            
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            for(String key : map.keySet()){
                params.add(new BasicNameValuePair(key,map.get(key)));
            }
            post.setEntity(new UrlEncodedFormEntity(params, CHARSET));
            
            HttpClient client = getHttpClient();
            HttpResponse response = client.execute(post);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
                throw new Exception("请求失败!");
            }
            
            HttpEntity resEntity = response.getEntity();
            return null == resEntity ? "" : EntityUtils.toString(resEntity,CHARSET);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }
    
}

以上是关于HttpClient的主要内容,如果未能解决你的问题,请参考以下文章

HttpClient怎么获取cookie

HttpClient 教程

httpclient 4.0 使用

从网络获取数据

httpclient设置超时。

Flurl Http 用法