1

我想知道如何能够在没有 SSL 证书验证的情况下将 POST 数据发送到 HTTPS URL,以及如何从该请求中取回 html(它实际上是 xml 数据)。

到目前为止,我有以下内容:

public void sendPost(final String request, final String urlParameters) throws IOException {

    URL url = new URL(request); 
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();           
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches (false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    connection.disconnect();        

}

所以我需要知道以下内容:

  • 如何忽略 ssl 证书验证
  • 如何从该请求中检索 html 数据

谢谢你

4

1 回答 1

1

基本上,您需要在以下位置设置自己HostnameVerifierHttpsUrlConnection

connection.setHostnameVerifier( new AlwaysTrustHostnameVerifier() );

在哪里

class AlwaysTrustHostnameVerifier implements X509TrustManager 
{
    public void checkClientTrusted( X509Certificate[] x509 , String authType ) throws CertificateException { /* nothing */ }
    public void checkServerTrusted( X509Certificate[] x509 , String authType ) throws CertificateException { /* nothing */ }
    public X509Certificate[] getAcceptedIssuers() { return null; }      
}

关键是如果证书链不受信任,则check*方法应该抛出CertificateException,在您的情况下应该忽略。

干杯,

于 2013-01-28T10:33:55.593 回答