Java SOAPConnection 调用 Https ASMX 服务

标签 java web-services ssl https tls1.2

下午好,

我已经为此工作了几个小时,我用谷歌搜索了又搜索,但没有成功。我有一个驻留在 https url 上的 ASMX 服务。我可以毫无问题地通过浏览器访问它,并查看 Web 方法和 WSDL。我尝试了几种方法来尝试通过 java 连接到端点,但仍然收到相同的 403 forbidden 错误。

这是我当前的代码:

public static String getInspectorSchedulesProd(){
    //Local Variable Declaration
    //List<InspectorSchedule> returnValue = null;
    String returnValue = "";
    //String url = "";
    String content = "";
    javax.xml.soap.SOAPConnectionFactory connectionFactory = null;
    javax.xml.soap.SOAPConnection connection = null;
    javax.xml.soap.SOAPMessage soapResponse = null;
    java.io.ByteArrayOutputStream out = null;

    try{
        javax.net.ssl.HttpsURLConnection httpsConnection = null;

        // Create SSL context and trust all certificates
        javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
        //content = "Current SSL Provider: " + sslContext.getProvider().getName() + "\n";

        for(java.security.Provider Item : java.security.Security.getProviders()){
            //content += Item.getName() + "\n";
        }

        javax.net.ssl.TrustManager[] trustAll = new javax.net.ssl.TrustManager[] {new TrustAllCertificates()};

        sslContext.init(null, trustAll, new java.security.SecureRandom());

        // Set trust all certificates context to HttpsURLConnection
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

        // Open HTTPS connection
        java.net.URL url = new java.net.URL("https://www.twiddy.com/webservices/rnsportalws1.asmx");
        httpsConnection = (javax.net.ssl.HttpsURLConnection) url.openConnection();

        // Trust all hosts
        httpsConnection.setHostnameVerifier(new TrustAllHosts());

        // Connect
        httpsConnection.connect();

        content = "Content Type: " + httpsConnection.getContentType() + "\nResponse Message:" + httpsConnection.getResponseMessage() + "\nAllow User Interaction:" + httpsConnection.getAllowUserInteraction();

        // Send HTTP SOAP request and get response
        //connection = javax.xml.soap.SOAPConnectionFactory.newInstance().createConnection();

        //soapResponse = connection.call(createGetInspectorsSchedulesSoapMessageProd(), "https://url/portalws1.asmx");

        //Write the results from the request into the output stream
        //soapResponse.writeTo(out);

        //Convert the stream into a string
        //content = new String(out.toByteArray());

        returnValue = content;

        // Close connection
        //connection.close();
        httpsConnection.disconnect();
    }
    catch (Exception ex){
        returnValue = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(ex);
    }

    return  returnValue;
}

private static class TrustAllCertificates implements javax.net.ssl.X509TrustManager {
    @Override
    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {

    }

    @Override
    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[]{};
    }
}

private static class TrustAllHosts implements javax.net.ssl.HostnameVerifier {
    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
        return true;
    }
}

private static javax.xml.soap.SOAPMessage createGetInspectorsSchedulesSoapMessageProd() throws Exception{
    //Local Variable Declaration
    String serverURI = "";
    javax.xml.soap.MessageFactory messageFactory = null;
    javax.xml.soap.SOAPMessage soapMessage = null;
    javax.xml.soap.SOAPPart soapPart = null;
    javax.xml.soap.SOAPEnvelope envelope = null;
    javax.xml.soap.SOAPBody soapBody = null;
    javax.xml.soap.SOAPElement soapBodyElem = null;
    javax.xml.soap.SOAPElement soapMethodParam = null;
    javax.xml.soap.MimeHeaders headers = null;

    //Set the Server Uri Namespace
    serverURI = "http://url/PortalWS1";

    //Init the Message Factory
    messageFactory = javax.xml.soap.MessageFactory.newInstance();

    //Init the Message
    soapMessage = messageFactory.createMessage();

    //Init the SOAP-specific portion of a Message
    soapPart = soapMessage.getSOAPPart();

    //Create the envelope that will wrap the message
    envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("PortalWS1Soap", serverURI);

    //Get an instance of the body of the message
    soapBody = envelope.getBody();

    //Add the Soap Method we wish to call
    soapBodyElem = soapBody.addChildElement("GetInspectorScheds", "PortalWS1Soap");

    //Add the Access Key Parameter
    soapMethodParam = soapBodyElem.addChildElement("strAccessKey", "PortalWS1Soap");
    soapMethodParam.addTextNode("SF!435gFW");

    //Get an instance of the http message headers
    headers = soapMessage.getMimeHeaders();

    //Append our soap Action header to the message
    headers.addHeader("soapAction", "https://url/webservices/portalws1.asmx/GetScheds");

    //Save our chnages
    soapMessage.saveChanges();

    return soapMessage;
}

enter image description here

先谢谢大家了!

最佳答案

我使用来自 here 的一等和二等
来自 AXIS 的 HostnameVerifier 类作为

    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return fias.HostnameVerifier.DEFAULT.verify(hostname, session);
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
    HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
    con.connect();

和来自 here 的类(class)用于发送 SOAP
制作你自己的 keyStore 和 trustStore
我通过 IP 进行连接,并为 key 使用别名(它们在商店中相同)
不要忘记用于调试 System.setProperty("javax.net.debug", "ssl");
它对我有用
附:my other simple method尚不适用于 SOAP ((
PSS:对于 SOAPAction header ,我使用的 uri 就像您的 serverURI。我的意思是命名空间+ Action

关于Java SOAPConnection 调用 Https ASMX 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564323/

相关文章:

java - 如何在没有ArrayIndexOutOfBoundsException的情况下通过executeBatch获取生成的键?

Java 8 流 - 或条件

java - 没有注释的 Jersey 方法参数

java - 学习WebServices的困惑!

ssl - 我必须在 Paypal 中使用 SSL 吗?如何在 Windows Azure 上设置 Paypal?

ssl - 支持 TLS : Kubernetes Ingress on GKE 的通配符域

iis - 有没有办法在没有通配符证书的情况下在同一台服务器上配置多个 SSL 站点?

java - findViewById() 上的空对象引用错误,即使在 setContentView() 之后调用也是如此

java - 在jsp页面中动态创建行

java - html 服务器 grizzly+jersey(.jar 存档中的 .html)