有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

不使用证书的java Htttps Post请求

当我试图用connnecion设置HostNameverifier时,会出现以下错误

HttpsURLConnection类型中的方法setHostnameVerifier(HostnameVerifier)不适用于参数(AlwaysTrustHostnameVerifier)enter image description here

 import java.io.DataInputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
 import java.net.URL;
 import java.net.URLEncoder;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.X509TrustManager;
 public class Https {
public static void main(String[] args) throws IOException {
    sendPost("https://*", "MBSUV aa123");
}
public  static void sendPost(final String request, final String urlParameters) throws IOException {
    URL url = new URL(request); 
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();  
    connection.setHostnameVerifier( new AlwaysTrustHostnameVerifier() );
    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();        
}
}
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; }      
}

共 (1) 个答案

  1. # 1 楼答案

    尝试使用

    connection.setHostnameVerifier((HostnameVerifier) new AlwaysTrustHostnameVerifier() );