欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpClient 的https 调用

程序员文章站 2022-06-21 21:11:57
...
package com.gpcsoft.xjmodule.utils;


import java.io.File;
import java.io.IOException; 
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException; 
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.HashMap; 
import java.util.List; 
import java.util.Map; 
 






import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.SSLContext; 
import org.apache.http.HttpEntity; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException;
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.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException; 
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.cert.X509Certificate;
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity; 
import org.apache.http.NameValuePair; 
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.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsClient {

private static final Logger log = LoggerFactory.getLogger(HttpsClient.class);

    public static final String get(final String url, final Map<String, Object> params) {
        StringBuilder sb = new StringBuilder("");

        if (null != params && !params.isEmpty()) {
            int i = 0;
            for (String key : params.keySet()) {
                if (i == 0) {
                    sb.append("?");
                } else {
                    sb.append("&");
                }
                sb.append(key).append("=").append(params.get(key));
                i++;
            }
        }

        CloseableHttpClient httpClient = createSSLClientDefault();

        CloseableHttpResponse response = null;
        HttpGet get = new HttpGet(url + sb.toString());
        String result = "";

        try {
            response = httpClient.execute(get);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            }
        } catch (IOException ex) {
        log.error(ex.getMessage());
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                log.error(ex.getMessage());
                }
            }
        }

        return result;
    }

    public  String postString(final String url, final Map<String, String> params) {
        CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost post = new HttpPost(url);

        CloseableHttpResponse response = null;

        if (null != params && !params.isEmpty()) {
            List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
                nvpList.add(nvp);
            }
            post.setEntity(new UrlEncodedFormEntity(nvpList, Charset.forName("UTF-8")));
        }

        String result = "";

        try {
            response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (null != entity) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
               
                log.info("result:"+result);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException ex) {
                log.error(ex.getMessage());
                }
            }
        }

        return result;
    }

    private static CloseableHttpClient createSSLClientDefault() {

        SSLContext sslContext;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string){
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyStoreException ex) {
        ex.printStackTrace();
        log.error(ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
        log.error(ex.getMessage());
        } catch (KeyManagementException ex) {
        ex.printStackTrace();
        log.error(ex.getMessage());
        }

        return HttpClients.createDefault();
    }
   
   
    public static void config(){
   
    // System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3,TLSv1.0,SSLv2");
    String path = System.getProperty("user.dir")+File.separator
    +"src/main/resources/sys"+File.separator+"log4j.properties";
   
   
    System.out.println("path::"+path);
   
    PropertyConfigurator.configure(path);
    }
   
    public static void zbxx() {
HttpsClient post = new HttpsClient();
try {

//String url = "http://192.168.2.215/msn/sendmsn.do";
// String url ="http://127.0.0.1:8000/m/msn/sendmsn.do";

//String url ="http://ztest.esgcc.com.cn:64515/m/msn/sendmsn.do";

String url ="https://dl.guowang.com:8443/springmvc/msn/sendmsn.do";

Map<String, String> param = new HashMap<String, String>();
param.put("proId", "4028824263e2e26c0163e2e61c7b0008");
param.put("bag", "");
param.put("xjUrl",
"https://z.esgcc.com.cn/XjPortalHome.do?method=indexAction&rp=10&page=1");
String name = URLEncoder.encode("*发送短信13", "UTF-8");
param.put("name", name);
param.put("code", "zbxx");

String result = post.postString(url, param);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
    public static void main(String[] args) {
    config();
    zbxx();
   

   
}
}


注意:一定要使用httpclient-4.3.5.jar,httpcore-4.3.2.jar。如果使用的话,每次调用的时候提示握手失败;

可以使用:httpclient-4.3.6.jar,httpcore-4.3.6.jar 本实例就是使用了这个版本。


Tomcat 版本配置SSL过程有两步
1用JDK自带的keytool.exe来生成私有密钥和自签发的证书,如下:
keytool -genkey -keyalg RSA -alias tomcat

2修改Tomcat的conf\server.xml文件,即增加下面一段

tomcat6 在server.xml

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
  keystroke="${user.home}/.keystore"  keystorePass="changeit"  />

tomcat7

  <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
   keystoreFile="${user.home}/.keystore"  keystorePass="changeit"
               clientAuth="false" sslProtocol="TLS" />


keystoreFile:证书存放位置
keystorePass:证书密码