使Apache HttpClient 4.3与sslSocketFactory / HostnameVerifier一起使用

时间:2014-05-07 20:20:37

标签: java ssl ssl-certificate apache-commons apache-httpclient-4.x

我正在开发一个Java程序,它将POST请求发送到一个网站供我公司使用。我们不拥有本网站,它们与我们分开。我一直在用各种方式来实际传递它想要的非常挑剔的参数,以便我从程序中完成它(而不是手动操作)。

我发现Apache HttpClient 4.3似乎是我尝试访问它的最佳途径,任何事情都会导致网站发出愤怒的回复,告诉我我的用户名和密码,而且无效/授权。

但后来我收到错误,因为站点证书不匹配,我联系了他们的支持,据说他们与另一个站点共享基础设施,因此预计证书不匹配。

所以我去了命令行并生成了一个密钥库,将其传递给程序,然后得到错误“java.security.cert.CertificateException:没有主题替代DNS名称匹配”。

有些狩猎让我使用了一个验证程序,它可以删除错误。

然后我意识到我不能让URLConnection / HttpsURLConnection和HttpClient / HttpPost一起工作。那就是我被困住的地方。我不知道如何使处理我的密钥库,TrustManager,SSLSocketFactory等的代码连接到我实际需要连接和POST的部分。

处理证书和验证的代码:

  InputStream in = new FileInputStream(new File("C:\\Program Files (x86)\\Java\\jre7\\bin\\my.keystore")); 
   KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 
    ks.load(in, "blahblah".toCharArray()); 
in.close(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
    tmf.init(ks);
     X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0]; 
     SSLContext context = SSLContext.getInstance("TLS"); 
     context.init(null, new TrustManager[] {defaultTrustManager}, null); 
     javax.net.ssl.SSLSocketFactory sslSocketFactory = context.getSocketFactory();

URL url = new URL("https://emailer.driveclick.com/dbadmin/xml_post.pl"); 

     URLConnection con = url.openConnection(); 
    ((HttpsURLConnection) con).setSSLSocketFactory(sslSocketFactory); 
   ((HttpsURLConnection) con).setHostnameVerifier(new Verifier());
     con.connect(); 
    in = con.getInputStream();

应该将我连接到网站的代码:

 try {
        //log into the website

        String url2 = "https://emailer.driveclick.com/dbadmin/xml_post.pl";
        HttpClient client = HttpClientBuilder.create().build();



        HttpPost post = new HttpPost(url2);


        post.setHeader("User-Agent", USER_AGENT);

        List<BasicNameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("username", "namefoo"));
        urlParameters.add(new BasicNameValuePair("api_password", "passfoo"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        org.apache.http.HttpResponse response = client.execute(post);

        System.out.println("\nSending 'POST' request to URL : " + url2);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
        {
            result.append(line);
        }
        System.out.println(result.toString());
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LastFileMove.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LastFileMove.class.getName()).log(Level.SEVERE, null, ex);
    }
编辑:我忘了包括我为我引用的Verifier所做的小班。

public class Verifier implements HostnameVerifier 
{

public boolean verify(String arg0, SSLSession arg1) {
        return true;   // mark everything as verified
}
}

2014年5月8日更新 SSLConext和Verifier现在设置如下:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .loadTrustMaterial(ks)
    .build(); 
X509HostnameVerifier verifier = new AbstractVerifier() 
{
@Override
public void verify(final String host, final String[] 
cns, final String[] subjectAlts) throws SSLException 
{
    verify(host, cns, subjectAlts, true);
}
};

我已经将我的HttpClient改为可关闭的一个:

CloseableHttpClient client = HttpClients.custom()
sslSocketFactory)
.setHostnameVerifier(verifier)
.setSslcontext(sslContext)
.build();

我回到了“javax.net.ssl.SSLException:证书中的主机名不匹配”错误。建议?

1 个答案:

答案 0 :(得分:4)

我不知道如何实现Verifier,但此代码段演示了如何创建自定义主机名验证程序HttpClient附带的任何内容都不能满足其需求

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = new FileInputStream(new File("C:\\Program Files (x86)\\Java\\jre7\\bin\\my.keystore"));
try {
    ks.load(in, "blahblah".toCharArray());
} finally {
    in.close();
}
SSLContext sslContext = SSLContexts.custom()
        .useTLS()
        .loadTrustMaterial(ks)
        .build();
X509HostnameVerifier verifier = new AbstractVerifier() {

    @Override
    public void verify(final String host, final String[] cns, final String[] subjectAlts) throws SSLException {
        verify(host, cns, subjectAlts, true);
    }

};

CloseableHttpClient hc = HttpClients.custom()
        .setSslcontext(sslContext)
        .setHostnameVerifier(verifier)
    .build();