得到"无法识别的Windows套接字错误:0:recv failed"发布消息时

时间:2017-08-21 12:45:57

标签: java ssl apache-httpclient-4.x mutual-authentication

我试图通过HttpClient将HTTP POST发布到启用了客户端身份验证的服务器上。这是我的代码

public class Send2Remote {

private static String sslMode = null;
private static String clientKeyStore = null;
private static String clientStoreType = null;
private static String clientStorePW = null;

private static String trustKeyStore = null;
private static String trustStoreType = null;
private static String trustStorePW = null;

public Send2Remote(String sslmode, String clientKS, String clientST, String clientTPW, 
        String trustKS, String trustST, String trustSPW) {
    sslMode = sslmode;
    clientKeyStore = clientKS;
    clientStoreType = clientST;
    clientStorePW = clientTPW;

    trustKeyStore = trustKS;
    trustStoreType = trustST;
    trustStorePW = trustSPW;
}

private final class X509HostnameVerifierImplementation implements X509HostnameVerifier {
    @Override
    public void verify(String host, SSLSocket ssl) throws IOException {
    }

    @Override
    public void verify(String host, X509Certificate cert) throws SSLException {
    }

    @Override
    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
    }

    @Override
    public boolean verify(String s, SSLSession sslSession) {
        return true;
    }
}

public String post(String uRL, List<NameValuePair> formparams) {        
    SSLContext sslContext = null;
    KeyManagerFactory kmf = null;
    TrustManagerFactory tmf = null;
    KeyStore ks = null;
    KeyStore tks = null;
    try {           
        sslContext = SSLContext.getInstance(sslMode);
        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        ks = KeyStore.getInstance(clientStoreType);
        tks = KeyStore.getInstance(trustStoreType);

        ks.load(new FileInputStream(clientKeyStore), clientStorePW.toCharArray());
        tks.load(new FileInputStream(trustKeyStore), trustStorePW.toCharArray());

        kmf.init(ks, clientStorePW.toCharArray());
        tmf.init(tks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e1) {
        Log4j.log.error("Error occurred: " + e1.getClass() + ":" + e1.getMessage() + ", Full Stacktrace: " + new Gson().toJson(e1.getStackTrace()));
        return null;
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext, new X509HostnameVerifierImplementation());

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory> create().register("https", sslsf)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(cm).build();

    HttpPost httppost = new HttpPost(uRL);

    UrlEncodedFormEntity uefEntity;
    String returnCode = null;
    try {
        uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(uefEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                returnCode = EntityUtils.toString(entity, "UTF-8");
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        Log4j.log.error("Error occurred: " + e.getClass() + ":" + e.getMessage() + ", Full Stacktrace: " + new Gson().toJson(e.getStackTrace()));
        return null;
    } catch (UnsupportedEncodingException e1) {
        Log4j.log.error("Error occurred: " + e1.getClass() + ":" + e1.getMessage() + ", Full Stacktrace: " + new Gson().toJson(e1.getStackTrace()));
        return null;
    } catch (IOException e) {
        Log4j.log.error("Error occurred: " + e.getClass() + ":" + e.getMessage() + ", Full Stacktrace: " + new Gson().toJson(e.getStackTrace()));
        return null;
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(httpclient);
        }
    }
    return returnCode;
}

public void close(Closeable io) {
    if (io != null) {
        try {
            io.close();
        } catch (IOException ignore) {
        }
    }
}

} 

当我使用自己的密钥库执行它时,发布消息

时出现异常
class javax.net.ssl.SSLHandshakeException:java.net.SocketException: Unrecognized Windows Sockets error: 0: recv failed

服务器管理员给了我他日志的一部分

[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, WRITE: TLSv1.2 Handshake, length = 96
[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, waiting for close_notify or alert: state 1
[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, Exception while waiting for close java.net.SocketException: Unrecognized Windows Sockets error: 0: recv failed
[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O %% Invalidated:  [Session-18, SSL_ECDHE_RSA_WITH_AES_256_CBC_SHA384]
[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
[2017/8/21   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, WRITE: TLSv1.2 Alert, length = 80
[2017/8/20   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, Exception sending alert: java.net.SocketException: Unrecognized Windows Sockets error: 0: socket write error
[2017/8/20   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, called closeSocket()
[2017/8/20   20:10:16:477 CST] 000000f7 SystemOut     O WebContainer : 20, handling exception: javax.net.ssl.SSLHandshakeException: java.net.SocketException: Unrecognized Windows Sockets error: 0: recv failed

服务器和我将彼此的证书添加到自己的信任密钥库中,因此它不应该是相互信任的问题。但我找不到其他可以解决这个问题的线索。

2 个答案:

答案 0 :(得分:0)

这可能会导致问题:

服务器是否启用了IPv4和IPv6?

<强>原因:

在Windows服务器上启用IPv4和IPv6时,Java虚拟机(JVM)在操作系统级别打开或关闭套接字时会出现问题。

可能的解决方法:

如果可能,JVM将需要在IPv4上运行。要执行此操作,请添加以下内容 JVM选项:
-Djava.net.preferIPv4Stack =真

答案 1 :(得分:0)

我收到了“ 0:接收失败”消息。我正在从一个线程读取套接字,然后在另一个线程上写入套接字。我重写了代码以始终从同一线程读取/写入套接字,而我再也没有这个问题了。