无法使用Java提交HTTPS帖子



我正在编写一些工具(仅用于开发环境),试图自动将消息提交到HTTPPost。我的方法(下面)sendByHTTPSNaive()使用javax.net.ssl.TrustManager的天真实现来接受任何证书。(同样,这是为了进行开发测试。)我正在取回一个未经授权的401代码。下面是我的方法和TLS握手的调试输出。项目网络人员告诉我,我只面对一个xml网关,天真的TrustManager应该通过它,但他们向我保证没有其他身份验证。如果是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调试输出=所有

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....
:...............

您的TLS工作正常,错误来自HTTP。您需要在请求的同时提供身份验证信息,特别是Authorization标头。响应包含一个"WWW-Authenticate"标头,该标头要求客户端提供凭据。客户端应该使用适当的"Authorization"标头重复请求。

最新更新