HttpClient HTTPS 工具类

原创 2017年11月14日 19:58:45


证书生成keyStore:
 keytool -import -v -file f:/ssl/clientkey.cer -keystore f:/ssl/tomcat.keystore

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.mail.internet.ParseException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.params.AuthParams;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import sun.util.logging.resources.logging;

public class HttpsClientProcessor2 {
    private static final Logger log = Logger.getLogger(HttpsClientProcessor2.class);

    HttpClient hc = null;
   
    
    /**
     * 设置信任自签名证书
     *   
     * @param keyStorePath      密钥库路径
     * @param keyStorepass      密钥库密码
     * @return
     */  
    public static SSLContext custom(String keyStorePath, String keyStorepass){  
        SSLContext sc = null;  
        FileInputStream instream = null;  
        KeyStore trustStore = null;  
        try {  
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());  
            instream = new FileInputStream(new File(keyStorePath));  
            trustStore.load(instream, keyStorepass.toCharArray());  
            // 相信自己的CA和所有自签名的证书  
            sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();  
        } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                instream.close();  
            } catch (IOException e) {  
            }  
        }  
        return sc;  
    }  
    
    
    //getRequest
    public static CloseableHttpResponse doHttpsGet(String url,String cookie,String refer) throws ClientProtocolException, IOException{
        String body = "";  
        
        //tomcat是我自己的密钥库的密码,你可以替换成自己的  
        //如果密码为空,则用"nopassword"代替  
        SSLContext sslcontext = custom("keystore路径", "密码"); 
         
           // 设置协议http和https对应的处理socket链接工厂的对象  
           Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
               .register("http", PlainConnectionSocketFactory.INSTANCE)  
               .register("https", new SSLConnectionSocketFactory(sslcontext))  
               .build();  
           PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
           HttpClients.custom().setConnectionManager(connManager);  
      
           //创建自定义的httpclient对象  
           HttpHost proxy = new HttpHost("172.17.18.80",8080,"http");

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setProxy(proxy).build();  
         //  CloseableHttpClient client = HttpClients.createDefault();  
        HttpGet get = new HttpGet(url);
//        get.setHeader("Content-type", "application/x-www-form-urlencoded");  
//        get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
        if(cookie != null){
            get.setHeader("Cookie",cookie);
        }
        if(refer != null){
            get.setHeader("Referer", refer);
        }
        CloseableHttpResponse response = client.execute(get);
        
        return response;
    }
    
    
    /**
     * 模拟请求
     *  
     * @param url       资源地址
     * @param map   参数列表
     * @param encoding  编码
     * @param referUrl
     * @param cookie1
     * @return
     * @throws ParseException
     * @throws IOException
     * @throws KeyManagementException  
     * @throws NoSuchAlgorithmException  
     * @throws ClientProtocolException  
     */  
    public static CloseableHttpResponse doHttpsPost(String url, Map<String,String> map,String encoding, String cookie1, String referUrl) throws ClientProtocolException, IOException {  
        String body = "";  
          
        //tomcat是我自己的密钥库的密码,你可以替换成自己的  
        //如果密码为空,则用"nopassword"代替  
        SSLContext sslcontext = custom("keystore路径", "密码");  
          
           // 设置协议http和https对应的处理socket链接工厂的对象  
           Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
               .register("http", PlainConnectionSocketFactory.INSTANCE)  
               .register("https", new SSLConnectionSocketFactory(sslcontext))  
               .build();  
           PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
           HttpClients.custom().setConnectionManager(connManager);  
      
           //创建自定义的httpclient对象  
           HttpHost proxy = new HttpHost("172.17.18.80",8080,"http");

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setProxy(proxy).build();  
         //  CloseableHttpClient client = HttpClients.createDefault();  
          
        //创建post方式请求对象  
        HttpPost httpPost = new HttpPost(url);  
          
        //装填参数  
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        if(map!=null){  
            for (Entry<String, String> entry : map.entrySet()) {  
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
            }  
        }  
        //设置参数到请求对象中  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));  
      
        log.info("请求地址:"+url);  
        log.info("请求参数:"+nvps.toString());  
          
        //设置header信息  
        //指定报文头【Content-type】、【User-Agent】  
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");  
//        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
        if(cookie1 != null){
            httpPost.setHeader("Cookie", cookie1);
        }
        if(referUrl != null){
            httpPost.setHeader("Referer", referUrl);
        }
//        if(url.indexOf("CreateSealDetailReport") != -1 ){//https://scnewb2b.travelsky.com/scb2b/CreateSealDetailReport.do
//            httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
//            httpPost.setHeader("Accept","*/*");
//        }
        
        //执行请求操作,并拿到结果(同步阻塞)  
        CloseableHttpResponse response = client.execute(httpPost);  
        //获取结果实体  
        return response;
    }  
    
}

相关文章推荐

基于HttpClient 4.3的可访问自签名HTTPS站点的新版工具类

HttpClient在当今Java应用中的位置越来越重要。从该项目的变迁过程我们不难发现,其已经从apache-commons众多的子项目中剥离,一跃成为如今的顶级项目,可见它的分量。然而随着项目的升...

swift3.0请求https工具类

  • 2016年12月12日 22:01
  • 4KB
  • 下载

Https请求验证工具类

  • 2017年07月24日 14:08
  • 3KB
  • 下载

java ssl双向验证httpclient客户端请求工具类

package com.juaicaiplus.ymfront.util; import java.io.FileInputStream; import java.io.FileNotFoundE...

Https请求工具类

  • 2017年01月03日 14:57
  • 20KB
  • 下载

模拟https请求工具类

  • 2014年07月03日 09:36
  • 9KB
  • 下载

HttpClient 操作工具类

设置post方法的header,增加红色字体部分的配置:  HttpClient client = new HttpClient();      client.getParams().setBoo...

okhttp关于https封装的几个工具类

  • 2016年12月28日 15:08
  • 1.43MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:HttpClient HTTPS 工具类
举报原因:
原因补充:

(最多只允许输入30个字)