https 发送get或post请求时忽略证书认证方式

原创地址:http://www.cnblogs.com/shipengzhi/archive/2012/08/22/2650953.html

在开发java时调用别人接口(这个接口还是https开头的)过程中,需要认证你的证书,然而测试服务器常常没有一个(有效的)SSL证书。在你的客户端连接测试服务器时,如下的异常会被抛出:”javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated”。

1.解决思路

我们将需要告诉client使用一个不同的TrustManager。TrustManager(http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/javax/net/ssl/TrustManager.html)是一个检查给定的证书是否有效的类。

SSL使用的模式是X.509(http://en.wikipedia.org/wiki/X.509),对于该模式Java有一个特定的TrustManager,称为X509TrustManager。首先我们需要创建这样的TrustManager。

下面我们需要找到一个将TrustManager设置到我们的HttpClient的方法。TrustManager只是被SSL的Socket所使用。Socket通过SocketFactory创建。对于SSL Socket,有一个SSLSocketFactory(http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/javax/net/ssl/SSLSocketFactory.html)。当创建新的SSLSocketFactory时,你需要传入SSLContext到它的构造方法中。在SSLContext中,我们将包含我们新创建的TrustManager。

首先我们需要得到一个SSLContext:

TLS是SSL的继承者,但是它们使用相同的SSLContext。

然后我们需要使用我们上面新创建的TrustManager来初始化该上下文:

最后我们创建SSLSocketFactory:

现在我们仍然需要将SSLSocketFactory注册到我们的HttpClient上。这是在SchemeRegistry中完成的:

我们注册了一个新的Scheme,使用协议https,我们新创建的SSLSocketFactory包含了我们的TrustManager,然后我们告诉HttpClienthttps的默认端口是443.


下面上代码:

1.使用的jar包:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.1.2</version>
</dependency>

2.在已有的util类中写:


/**
 * 避免HttpClient”SSLPeerUnverifiedException: peer not authenticated”异常
 * 不用导入SSL证书
 */
public static class WebClientPassWrapper {

    public static org.apache.http.client.HttpClient wrapClientPass(org.apache.http.client.HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SchemeRegistry registry = new SchemeRegistry();
            //https 
            registry.register(new Scheme("https", 443, ssf));
            //http
            registry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
            ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
            return new DefaultHttpClient(mgr, base.getParams());
        } catch (Exception ex) {
            System.out.println("WebClientPassWrapper"+"创建忽略用户证书的HttpClient对象失败,尝试创建普通HttpClient对象");
            ex.printStackTrace();
            return new DefaultHttpClient();
        }
    }
}

3:使用方式:

/**
 * http请求工具类,get请求
 * @param url
 * @param params
 * @param resonseCharSet
 * @return
 * @throws Exception
 */
public static String httpGet(String url, Map<String, Object> params,String ...resonseCharSet) throws Exception {
    DefaultHttpClient defaultHttpClient = null;
    BufferedReader bufferedReader = null;
    try {
        defaultHttpClient = new DefaultHttpClient();
        if(params!=null){
            StringBuilder stringBuilder=new StringBuilder();
            Iterator<String> iterator=params.keySet().iterator();
            String key;
            while (iterator.hasNext()){
                key=iterator.next();
                Object val=params.get(key);
                if(val instanceof List){
                    List v= (List) val;
                    for (Object o:v){
                        stringBuilder.append(key).append("=").append(o.toString()).append("&");
                    }
                }else{
                    stringBuilder.append(key).append("=").append(val.toString()).append("&");
                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            url=url+"?"+stringBuilder.toString();
            log.info("url:{}",url);
        }
        //调用忽略认证证书
        defaultHttpClient= (DefaultHttpClient) WebClientPassWrapper.wrapClientPass(defaultHttpClient);
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=ut-8");
        HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            String errorLog="请求失败,errorCode:"+httpResponse.getStatusLine().getStatusCode();
            log.info(errorLog);
            throw new Exception(url+errorLog);
        }
        //读取返回信息
        String charSet="utf-8";
        if(resonseCharSet!=null && resonseCharSet.length>0)
            charSet=resonseCharSet[0];
        String output;
        bufferedReader=new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),charSet));

        StringBuilder dataBuilder=new StringBuilder();
        while ((output=bufferedReader.readLine())!=null){
            dataBuilder.append(output);
        }
        return dataBuilder.toString();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw e;
    }catch (IOException e){
        e.printStackTrace();
        throw e;
    }finally {
        if(defaultHttpClient!=null)
            defaultHttpClient.getConnectionManager().shutdown();
        if(bufferedReader!=null)
            bufferedReader.close();
    }
}


到这里就结束了,也是借鉴别人的思路,可以动手试试
发布了15 篇原创文章 · 获赞 6 · 访问量 2万+
展开阅读全文

Java 访问 Https接口 忽略证书

09-05

``` /** * 证书信任管理器(用于https请求) * @date 2013-08-08 */ public class MyX509TrustManager implements X509TrustManager{ public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (ConnectException ce) { ce.printStackTrace(); // log.error("Weixin server connection timed out."); } catch (Exception e) { //log.error("https request error:{}", e); e.printStackTrace(); } return jsonObject; } public static void main(String[] args) { System.err.println(httpRequest("https://moni.byxgj.com:23134", "GET", null)); ///createaccount?requestid=1&sa=sa07&sapass=c33&account=0&password=123456&name=张三&group=交易组1&mainaccount=21 } } ``` ``` javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching moni.byxgj.com found at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source) at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source) at sun.security.ssl.Handshaker.processLoop(Unknown Source) at sun.security.ssl.Handshaker.process_record(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source) at com.wlq.test.MyX509TrustManager.httpRequest(MyX509TrustManager.java:57) at com.wlq.test.MyX509TrustManager.main(MyX509TrustManager.java:94) ``` 请问这个错怎么整?网上的方法全部测试过来了 ``` httpClient方法 报 javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated ``` ps:如果有直接可用demo,求分享 问答

C#调用https接口证书验证不通过问题

10-18

java通过证书调用https的接口,C#能实现吗?我C#尝试调用,一直报错“ssl通道建立时出现未知错误” package com.jit.szlb.util.client; import java.rmi.RemoteException; import javax.xml.namespace.QName; import javax.xml.rpc.ServiceException; import javax.xml.rpc.encoding.XMLType; import net.sf.json.JSONObject; import org.apache.axis.client.Call; import org.apache.axis.client.Service; public class TestClient { public static void main(String[] args) throws ServiceException, RemoteException { String basePath = TestClient.class.getResource("").getPath(); System.setProperty("javax.net.ssl.keyStoreType","pkcs12"); System.setProperty("javax.net.ssl.keyStore",basePath + "anjianshuju.pfx"); System.setProperty("javax.net.ssl.keyStorePassword","11111111"); System.setProperty("javax.net.ssl.trustStoreType","jks"); System.setProperty("javax.net.ssl.trustStore",basePath + "127.0.0.1.jks"); System.setProperty("javax.net.ssl.trustStorePassword","11111111"); Service service=new Service(); Call call=(Call)service.createCall(); call.setTargetEndpointAddress("https://139.215.205.50/iservice/webservice/iservice?wsdl"); call.setSOAPActionURI("http://service.jkfwpt.jit.com/serverService"); call.setUseSOAPAction(true); call.setOperationName(new QName("http://service.jkfwpt.jit.com/", "serverService")); call.setReturnType(XMLType.XSD_STRING); call.addParameter("xtid", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("fwid", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter("param", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); JSONObject obj = new JSONObject(); obj.put("queryCode", "mg0412kv"); String str = (String)call.invoke(new Object[]{"8a81a7c5576583be01576589ea260001","8a81a7c5576583be01576949f9d80002",""}); System.out.println(str); } } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览