HttpClient4.3.6版本以上的http和https请求写法

来源:互联网 发布:eclipse java ee 64位 编辑:程序博客网 时间:2024/06/06 12:32
importjava.io.IOException;
importjava.io.UnsupportedEncodingException;
importjava.security.cert.CertificateException;
importjava.security.cert.X509Certificate;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
 
importjavax.net.ssl.SSLContext;
importjavax.servlet.http.HttpServletRequest;
 
importorg.apache.http.Consts;
importorg.apache.http.HttpEntity;
importorg.apache.http.NameValuePair;
importorg.apache.http.ParseException;
importorg.apache.http.client.config.RequestConfig;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;
importorg.apache.http.conn.ssl.SSLContextBuilder;
importorg.apache.http.conn.ssl.TrustStrategy;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;
importorg.apache.http.message.BasicHeader;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
 
importcom.jfinal.kit.StrKit;
 
publicclass HttpUtil {
     
    privatestatic final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    // 连接超时时间
    privatestatic final int CONNECTION_TIMEOUT = 3000;//3秒
    // 读数据超时时间
    privatestatic final int READ_DATA_TIMEOUT = 6000;//6秒
     
    privatestatic PoolingHttpClientConnectionManager connManager = null;
    privatestatic CloseableHttpClient httpclient = null;
    static{
        connManager = newPoolingHttpClientConnectionManager();
        httpclient = HttpClients.custom().setConnectionManager(connManager).build();
    }
    /**
     * sslClient
     * @return
     */
    publicstatic CloseableHttpClient createSSLClient() {
        try{
            SSLContext sslContext = newSSLContextBuilder().loadTrustMaterial(null,newTrustStrategy() {
                //信任所有
                @Override
                publicboolean isTrusted(X509Certificate[] chain,String authType) throwsCertificateException {
                    returntrue;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = newSSLConnectionSocketFactory(sslContext ,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            returnHttpClients.custom().setSSLSocketFactory(sslsf).build();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }
    /**
     * Post请求(默认超时时间)
     * @param url
     * @param data
     * @param encoding
     * @return
     */
    publicstatic String post(String url,  Map<String, Object> data, String encoding) throwsIOException{
        returnpost(url, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, data, encoding);
    }
    publicstatic String post(String url, inttimeout ,Map<String, Object> data, String encoding) throwsIOException{
        returnpost(url, timeout, timeout, data, encoding);
    }
    /**
     * Post请求
     * @param url
     * @param connectTimeout
     * @param readTimeout
     * @param data
     * @param encoding
     * @return
     * @throws IOException
     * @throws ParseException
     */
    publicstatic String post(String url, intconnectTimeout, intreadTimeout,Map<String, Object> data, String encoding) throwsIOException{
        HttpPost post = newHttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(readTimeout)
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout)
                .setExpectContinueEnabled(false).build();
        post.setConfig(requestConfig);
         
        if(null!=data && !data.isEmpty()) {
             List<NameValuePair> formparams = newArrayList<NameValuePair>();
             for(String key : data.keySet()){
                 formparams.add(newBasicNameValuePair(key, data.get(key).toString()));
             }
             UrlEncodedFormEntity formEntity = newUrlEncodedFormEntity(formparams, encoding);
             post.setEntity(formEntity);
        }
        CloseableHttpResponse response = null;
        if(url.startsWith("https")){//https
            response = createSSLClient().execute(post);
        }else{
            response = httpclient.execute(post);
        }
         
        HttpEntity entity = response.getEntity();
        try{
            if(entity != null){
                 String str = EntityUtils.toString(entity, encoding);
                 returnstr;
           }
        }finally{
            if(entity != null){
               entity.getContent().close();
           }
           if(response != null){
               response.close();
           }
       }
        returnnull;
    }
    /**
     * 如果失败尝试3次
     * @param url
     * @param encoding
     * @return
     */
    publicstatic String tryGet(String url, String encoding){
        String resultStr = "";
        for(inti = 0; i < 3; i++) {
            try{
                resultStr  = get(url, encoding);
                break;
            }catch(Exception e) {
                logger.error("请求异常count:{} ",i,e);
            }
        }
        returnresultStr;
    }
    /**
     * Post请求(默认超时时间)
     * @param url
     * @param data
     * @param encoding
     * @return
     */
    publicstatic String get(String url, String encoding)  throwsIOException {
        returnget(url , null, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, encoding);
    }
    publicstatic String get(String url, Map<String, String> cookies, String encoding) throwsIOException {
        returnget(url , cookies, CONNECTION_TIMEOUT, READ_DATA_TIMEOUT, encoding);
    }
    publicstatic String get(String url, Map<String, String> cookies,inttimeout , String encoding) throwsIOException {
        returnget(url, cookies, timeout, timeout, encoding);
    }
    publicstatic String get(String url,Map<String, String> cookies ,intconnectTimeout, intreadTimeout, String encoding) throwsIOException {
        HttpGet get = newHttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(readTimeout)
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout)
                .setExpectContinueEnabled(false).build();
        get.setConfig(requestConfig);
        if(cookies !=null&& !cookies.isEmpty()){
            StringBuilder buffer = newStringBuilder(128);
            for(String cookieKey : cookies.keySet()){
                buffer.append(cookieKey).append("=").append(cookies.get(cookieKey)).append("; ");
            }
            // 设置cookie内容
            get.setHeader(newBasicHeader("Cookie",buffer.toString()));
        }
       CloseableHttpResponse response = null;
        if(url.startsWith("https")){//https
            response = createSSLClient().execute(get);
        }else{
            response = httpclient.execute(get);
        }
        HttpEntity entity = response.getEntity();
        try{
             if(entity != null){
                  String str = EntityUtils.toString(entity, encoding);
                  returnstr;
            }
        }finally{
            if(entity != null){
                entity.getContent().close();
            }
            if(response != null){
                response.close();
            }
        }
         
        returnnull;
    }
    /**
     * sslClient
     * @return
     */
    publicstatic String postBody(String url, String body, String encoding, intconnectTimeout, intreadTimeout) throwsIOException{
        HttpPost post = newHttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(readTimeout)
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout)
                .setExpectContinueEnabled(false).build();
        post.setConfig(requestConfig);
         
        if(StrKit.notBlank(body)) {
            StringEntity formEntity = newStringEntity(body, encoding);
            post.setEntity(formEntity);
        }
         
        CloseableHttpResponse response = null;
        if(url.startsWith("https")){//https
            response = createSSLClient().execute(post);
        }else{
            response = httpclient.execute(post);
        }
         
        HttpEntity entity = response.getEntity();
        try{
            if(entity != null){
                 String str = EntityUtils.toString(entity, encoding);
                 returnstr;
           }
        }finally{
            if(entity != null){
               entity.getContent().close();
           }
           if(response != null){
               response.close();
           }
       }
        returnnull;
    }
    /**
     * map转成queryStr
     * @param paramMap
     * @return
     * @throws UnsupportedEncodingException
     */
    publicstatic String mapToQueryStr(Map<String,String> paramMap) {
        StringBuffer strBuff = newStringBuffer();
        for(String key : paramMap.keySet()) {
            strBuff.append(key).append("=").append(paramMap.get(key)).append("&");
        }
        returnstrBuff.substring(0, strBuff.length()-1);
    }
     
}
0 0
原创粉丝点击