无法使用Java提交HTTPS帖子

时间:2016-05-02 15:39:23

标签: java-8 tls1.2

我正在编写一些工具(仅用于开发环境),我试图自动将消息提交到HTTP Post。我的方法(下面)sendByHTTPSNaive()使用javax.net.ssl.TrustManager的简单实现来接受任何证书。 (同样,这是用于开发测试。)我收到了401未经授权的代码。下面是我的方法和TLS握手的调试输出我相信。项目网络人员告诉我,我只面对一个天真的TrustManager应该通过的xml网关,但我确信没有其他身份验证。如果它是一些TLS的东西,或者除了xml网关之外还有另一个身份验证层,我已经用尽了如何调试这个问题的想法?

public String sendByHTTPSNaive(String destinationURI,
                                String msgBodyContent) {

    String result = "no response";
    try {
        URL url = new URL(destinationURI);
        // URLConnection con = url.openConnection();

        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // specify that we will send output and accept input
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setConnectTimeout(20000); // long timeout, but not infinite
        con.setReadTimeout(20000);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);

        NoopHostnameVerifier HOSTNAME_VERIFIER = new NoopHostnameVerifier();
        TrustManager[] TRUST_MANAGER = { new NaiveTrustManager() };
        if (con instanceof HttpsURLConnection) {

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], TRUST_MANAGER,
                                            new SecureRandom());
            SSLSocketFactory socketFactory = context.getSocketFactory();
            ((HttpsURLConnection) con).setSSLSocketFactory(socketFactory);
            ((HttpsURLConnection) con).setHostnameVerifier(HOSTNAME_VERIFIER);
        }

        // tell the web server what we are sending
        con.setRequestProperty("Content-Type", "text/xml");
        OutputStreamWriter writer = new OutputStreamWriter(
                                        con.getOutputStream());
        writer.write(msgBodyContent);
        writer.flush();
        writer.close();

        // reading the response
        InputStreamReader reader = new InputStreamReader(con.getInputStream());
        StringBuilder buf = new StringBuilder();

        char[] cbuf = new char[2048];
        int num;

        while (-1 != (num = reader.read(cbuf))) {
            buf.append(cbuf, 0, num);
        }

        result = buf.toString();
    } catch (Throwable t) {
        t.printStackTrace(System.out);
    }
    return result;
}

使用标志-Djavax.net.debug = all

调试输出
HTTP/1.1 401 Una
uthorized..Serve
r: Apache-Coyote
/1.1..WWW-Authen
ticate: Basic re
alm="L7SSGBasicR
ealm"..L7-Policy
-URL: https://ab
cdefghi.jklmno.c
om:443/ssg/polic
y/disco?serviceo
id=20938758..Con
tent-Length: 23.
.Date: Thu, 28 A
pr 2016 16:00:56
GMT....Authenti
cation RequiredC
..._.2..5\"B....
:...............

1 个答案:

答案 0 :(得分:0)

您的TLS工作正常,错误来自HTTP。您需要提供身份验证信息以及请求 - 特别是Authorization标头。该回复包含一个“WWW-Authenticate”'标头 - 这是挑战客户端提供凭据。客户应该通过适当的“授权”重复请求。报头中。