码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient

时间:2016-08-29 09:09:04      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/zhc-hnust/p/5816627.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!