javax.net.ssl.SSLPeerUnverifiedException:对等体未在jdk7中进行身份验证,但未在jdk8

时间:2017-03-31 16:24:56

标签: java ssl httpclient socketexception connection-reset

HttpClient =new DefaultHttpClient();
HttpPost post = new HttpPost("https://myulr/token");
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair("client_id","my-client-id"));
parametersBody.add(new BasicNameValuePair("client_secret","my-secret-key"));
parametersBody.add(new BasicNameValuePair("scope","my-scope"));
parametersBody.add(new BasicNameValuePair("grant_type","client_credentials"));
try{
    post.setEntity(new UrlEncodedFormEntity(parametersBody));
    HttpResponse httpResponse = httpClient.execute(post);
    int code = httpResponse.getStatusLine().getStatusCode();
    System.out.println("Code::::: "+code);
    String result=EntityUtils.toString(httpResponse.getEntity());
    System.out.println("Result: "+result); 
 }catch(Exception e){
    e.printStackTrace();
 }

此代码在JDK8中正确执行,但如果我尝试在JDK7中执行它,则会抛出javax.net.ssl.SSLPeerUnverifiedException:peer not authenticated exception。我试图谷歌这个问题。我发现我们可以编写X509TrustManager和X509HostnameVerifier。我也试过这些实现,但仍然无法正常工作。请建议我如何在JDK7中执行它。 再次,如果我用X509TrustManager和X509HostnameVerifier执行代码,我得到“java.net.SocketException:Connection reset”

1 个答案:

答案 0 :(得分:0)

我刚刚研究了这个,我想补充一点 - 支持TLS 1.2首先出现在JDK 7中。出于兼容性原因,它默认在服务器套接字上启用,但在客户端上禁用。 为了改变它,我编写了以下代码,它对我有用:

HttpClient base = new DefaultHttpClient();
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
X509TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
    }
    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
    }
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
 };
 X509HostnameVerifier verifier = new X509HostnameVerifier() {
     @Override
     public void verify(String string, X509Certificate xc) throws SSLException {
     }
     @Override
     public void verify(String string, String[] strings, String[] strings1) throws SSLException {
     }
     @Override
     public boolean verify(String string, SSLSession ssls) {
         return true;
     }
     @Override
     public void verify(String arg0, SSLSocket arg1) throws IOException {
     }
 };
 ctx.init(null, new TrustManager[]{tm}, null);
 SSLSocketFactory ssf = new 
 SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 ssf.setHostnameVerifier(verifier);
 ClientConnectionManager ccm = base.getConnectionManager();
 SchemeRegistry sr = ccm.getSchemeRegistry();
 sr.register(new Scheme("https", ssf, 443));
 httpClient = new DefaultHttpClient(ccm, base.getParams());