0
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 异常。我试图用谷歌搜索这个问题。我发现我们可以写 X509TrustManager 和 X509HostnameVerifier。我也尝试了这些实现,但仍然没有工作。请建议我如何在JDK7中执行它。如果我再次使用 X509TrustManager 和 X509HostnameVerifier 执行代码,我会得到“java.net.SocketException:连接重置”

4

1 回答 1

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());
于 2017-04-04T20:14:07.373 回答