| 
| 
查看: 1195|回复: 2
 | 
Web Service Connection Reset Problem
[复制链接] |  
 |  | 
 
| Dear All, Sorry to write this in english because of my company PC is not able to write in chinese.
 The scenario is I need to write a webservice client to send request to a third party server and the third party server will returns the result back to my server.
 However, I got the connection reset error while trying to perform connection to the third party server.
 I am using Java 1.5 IBM and our web server is running on Oracle iPlanet Web Server 7.0.13.
 The code to send the request from my side
 The HttpsURLConnectionFactory code复制代码try
                {
                        int intStatus;
                        String szResMsg;
                        String szResContent;
                        
                        HttpsURLConnectionFactory factory = new HttpsURLConnectionFactory("https://someuri", "someuri.com.my", path to the truststore", "password for the truststore");                        
                
                        StringBuffer sbPost = new StringBuffer();
                        sbPost.append(jsonObject.toString());
                        
                factory.setRequestContent(sbPost.toString().getBytes());
                factory.setRequestMethod("POST");                
                factory.setRequestProperty("content-type", "text/json");
                
                intStatus = factory.connect();
                        
                szResMsg = factory.getResponseMessage();
                szResContent = factory.getResponseContent();                
                
                logger.info("reading status: [" + intStatus + "]");
                logger.info("reading reply msg: [" + szResMsg + "]");
                logger.info("reading reply content: [" + szResContent + "]");
                }
                catch(Exception e)
                {
                        logger.error("WSJsonParserServlet.sendJSONToWSServer: " + e.getMessage());
                        e.printStackTrace();
                        return false;
                }
and the error returned复制代码public class HttpsURLConnectionFactory
{
    private static final String DEFAULT_KEYSTORE_TYPE   = "JKS";
    private static final String DEFAULT_ALGORITHM       = "SunX509";
    private static final String DEFAULT_SSL_PROTOCOL    = "TLS";
    private static final String DEFAULT_SSL_PROVIDER    = "SunJSSE";
    private String strURL                               = null;
    private HttpsURLConnection httpsURLConnection       = null;
    private String strTrustedHost                       = null;
    private String strKeyStore                          = null;
    private String strKeyStorePassword                  = null;
    private String strKeyPassword                       = null;
    private boolean bMutualAuth                         = false;
    private boolean bProxyExists                        = false;
    private String strProxyAuthCredential               = null;
    private String strRequestMethod                     = "GET";
    private Hashtable hRequestProperties                = null;
    private int intResponseCode                         = 0;
    private String strResponseContent                   = null;
    private String strResponseMessage                   = null;
    private Hashtable hResponseHeaders                  = new Hashtable();
    private byte[] bContent                             = null;
    
    private String strRequestPropertyKey                = null;
    private String strRequestPropertyValue              = null;
    private PBBLogger logger = PBBLogger.getInstance();
    public HttpsURLConnectionFactory(String strURL)
    {
        this.strURL = strURL;
    }
    public HttpsURLConnectionFactory(String strURL, String strTrustStore, String strTrustStorePassword)
            throws Exception
    {
        this.strURL = strURL;
        setSystemProperties();
        setTrustStore(strTrustStore, strTrustStorePassword);
    }
    public HttpsURLConnectionFactory(String strURL, String strTrustedHost, String strTrustStore,
            String strTrustStorePassword) throws Exception
    {
        this.strURL = strURL;
        this.strTrustedHost = strTrustedHost;
        setSystemProperties();
        setTrustStore(strTrustStore, strTrustStorePassword);
    }
    public HttpsURLConnectionFactory(String strURL, String strTrustStore, String strTrustStorePassword,
            String strKeyStore, String strKeyStorePassword, String strKeyPassword) throws Exception
    {
        this.strURL = strURL;
        this.strKeyStore = strKeyStore;
        this.strKeyStorePassword = strKeyStorePassword;
        this.strKeyPassword = strKeyPassword;
        this.bMutualAuth = true;
        setSystemProperties();
        setTrustStore(strTrustStore, strTrustStorePassword);
    }
    public HttpsURLConnectionFactory(String strURL, String strTrustedHost, String strTrustStore,
            String strTrustStorePassword, String strKeyStore, String strKeyStorePassword, String strKeyPassword)
            throws Exception
    {
        this.strURL = strURL;
        this.strTrustedHost = strTrustedHost;
        this.strKeyStore = strKeyStore;
        this.strKeyStorePassword = strKeyStorePassword;
        this.strKeyPassword = strKeyPassword;
        this.bMutualAuth = true;
        setSystemProperties();
        setTrustStore(strTrustStore, strTrustStorePassword);
    }
    /***************************************************************************
     * <p>
     * Set the system property for proxy.
     * </p>
     *
     * @Param String
     *            strProxyHost : Proxy host to tunnel through
     * @Param String
     *            strProxyPort : Proxy port to tunnel through
     **************************************************************************/
    public void setProxy(String strProxyHost, int intProxyPort)
    {
        System.setProperty("https.proxyHost", strProxyHost);
        System.setProperty("https.proxyPort", String.valueOf(intProxyPort));
        bProxyExists = true;
        logger.info("HttpsURLConnectionFactory.setProxy:Proxy Host is : [" + strProxyHost + "]");
        logger.info("HttpsURLConnectionFactory.setProxy:Proxy Port is : [" + intProxyPort + "]");
    }
    public void addProxyCredential(String strUsername, String strPassword)
    {
        String strUsernamePassword = strUsername + ":" + strPassword;
        strProxyAuthCredential = "Proxy-Authorization: Basic "
                + new sun.misc.BASE64Encoder().encode(strUsernamePassword.getBytes());
        logger.info("HttpsURLConnectionFactory.addProxyCredential:Proxy Username is :[" + strUsername + "]");
        logger.info("HttpsURLConnectionFactory.addProxyCredential:Proxy Password is :[" + strPassword + "]");
    }
    public void setConnectionTimeout(int intConnectionTimeout)
    {
    }
    public void setRequestMethod(String strRequestMethod)
    {
        this.strRequestMethod = strRequestMethod;
        logger.info("HttpsURLConnectionFactory.setRequestMethod:Request Method is :[" + strRequestMethod + "]");
    }
    public void setRequestProperties(Hashtable hRequestProperties)
    {
        this.hRequestProperties = hRequestProperties;
    }
    
    public void setRequestContent(byte[] bContent)
    {
        this.bContent = bContent;
    }
    
    public void setRequestProperty(String strRequestPropertyKey, String strRequestPropertyValue)
    {
            this.strRequestPropertyKey = strRequestPropertyKey;
            this.strRequestPropertyValue = strRequestPropertyValue;
    }
    public HttpsURLConnection openConnection() throws Exception
    {
        try
        {
            logger.info("HttpsURLConnectionFactory.openConnection:Opening connection...");
            URL url = null;
            try
            {
                url = new URL(getURL());
            }
            catch (MalformedURLException e)
            {
                logger.error("HttpsURLConnectionFactory.openConnection:Exception - " + e.getMessage());
                throw new Exception("HttpsURLConnectionFactory.openConnection:Invalid url address", e);
            }
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
            // Host name vs CN in certificate verification.If trusted host is
            // defined, HostNameVerifier will compare
            // trusted host against certificate host name, else host in url will
            // be compared against certificate host name.
            httpsURLConnection.setHostnameVerifier(new TrustedHostVerifier(strTrustedHost));
            // tunnel through proxy
            if (bProxyExists)
            {
                if (strProxyAuthCredential == null)
                {
                    httpsURLConnection.setSSLSocketFactory(new SSLTunnelSocketFactory(System
                            .getProperty("https.proxyHost"), System.getProperty("https.proxyPort")));
                }
                else
                {
                    httpsURLConnection.setSSLSocketFactory(new SSLTunnelSocketFactory(System
                            .getProperty("https.proxyHost"), System.getProperty("https.proxyPort"),
                            strProxyAuthCredential));
                }
            }
            // set mutual authentication if remote peer require client
            // authentication
            if (bMutualAuth)
            {
                setMutualAuthentication(httpsURLConnection, strKeyStore, strKeyStorePassword, strKeyPassword);
            }
            // setting request method
            try
            {
                httpsURLConnection.setRequestMethod(strRequestMethod);
            }
            catch (ProtocolException e)
            {
                throw new Exception("HttpsURLConnectionFactory.openConnection:Set request method fail.", e);
            }
            // setting request property
            if (hRequestProperties != null)
            {
                for (Enumeration e = hRequestProperties.keys(); e.hasMoreElements();)
                {
                    String strRequestProperty = (String) e.nextElement();
                    httpsURLConnection.setRequestProperty(strRequestProperty, (String) hRequestProperties
                            .get(strRequestProperty));
                }
            }
            
            // set single request property
            if(strRequestPropertyKey != null)
            {
                    httpsURLConnection.setRequestProperty(strRequestPropertyKey, strRequestPropertyValue);
            }
            
            httpsURLConnection.setDoInput(true);
            httpsURLConnection.setDoOutput(true);
            httpsURLConnection.setUseCaches(false);
            if (bContent != null)
            {
                OutputStream out = httpsURLConnection.getOutputStream();
                out.write(bContent);
                out.flush();
                out.close();
            }            
            setConnectionObject(httpsURLConnection);
        }
        catch (IOException e)
        {
            logger.error("HttpsURLConnectionFactory.openConnection:Exception - " + e.getMessage());
            throw new Exception("HttpsURLConnectionFactory.openConnection fail.", e);
        }
        return httpsURLConnection;
    }
    /***************************************************************************
     * <p>
     * Get reply message from remote peer.
     * </p>
     *
     * @return String : Reply message from remote peer
     **************************************************************************/
    public int connect() throws Exception
    {
        HttpsURLConnection httpsURLConnection = getConnectionObject();
        if (httpsURLConnection == null)
        {
            httpsURLConnection = openConnection();
        }
        // Connecting to url
        try
        {
            logger.info("HttpsURLConnectionFactory.connect:Connecting...");
            httpsURLConnection.connect();
        }
        catch (IOException e)
        {
            logger.error("HttpsURLConnectionFactory.connect:Exception - " + e.getMessage());
            throw new Exception("HttpsURLConnectionFactory:fail.", e);
        }
        // Reading reply from remote server
        try
        {
            logger.info("HttpsURLConnectionFactory.connect:Reading reply...");
            intResponseCode = httpsURLConnection.getResponseCode();
            setResponseMessage(httpsURLConnection.getResponseMessage());
            int i=1;
            while (httpsURLConnection.getHeaderField(i) != null)
            {
                hResponseHeaders.put(httpsURLConnection.getHeaderFieldKey(i).toUpperCase(), httpsURLConnection.getHeaderField(i));
                i++;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
            String strResponseContent = new String();
            for (String strTemp = null; (strTemp = reader.readLine()) != null;)
            {
                strResponseContent += strTemp + "\n";
            }
            if (!strResponseContent.equals(""))
            {
                strResponseContent = strResponseContent.substring(0, strResponseContent.lastIndexOf("\n"));
            }
            setResponseContent(strResponseContent);
            reader.close();
        }
        catch (IOException e)
        {
            logger.error("HttpsURLConnectionFactory.connect:Exception - " + e.getMessage());
            throw new Exception("HttpsURLConnectionFactory.connect:Fail to get reply from remote peer", e);
        }
        logger.info("HttpsURLConnectionFactory.connect:Disconnecting...");
        httpsURLConnection.disconnect();
        return intResponseCode;
    }
    public void setConnectionObject(HttpsURLConnection httpsURLConnection)
    {
        this.httpsURLConnection = httpsURLConnection;
    }
    public HttpsURLConnection getConnectionObject()
    {
        return this.httpsURLConnection;
    }
    public String getResponseMessage()
    {
        return this.strResponseMessage;
    }
    public String getResponseContent()
    {
        return this.strResponseContent;
    }
    public String getResponseHeader(String strHeader)
    {
        if (hResponseHeaders.containsKey(strHeader))
        {
            return (String)hResponseHeaders.get(strHeader);
        }
        else
        {
            return null;
        }
    }
    private String getURL()
    {
        return this.strURL;
    }
    private void setResponseMessage(String strResponseMessage)
    {
        this.strResponseMessage = strResponseMessage;
    }
    private void setResponseContent(String strResponseContent)
    {
        this.strResponseContent = strResponseContent;
    }
    /***************************************************************************
     * <p>
     * Set the related system properties values.
     * </p>
     **************************************************************************/
    private void setSystemProperties()
    {
        System.setProperty("javax.net.debug", "all");
        //System.setProperty("https.protocols", "TLSv1");
        // provider
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        System.setProperty("java.protocol.handler.pkgs","javax.net.ssl");
    }
    /***************************************************************************
     * <p>
     * Set truststore properties into system properties.
     * </p>
     *
     * @param String
     *            strtTrustStore : Truststore path
     * @param String
     *            strTrustStorePassword : Truststore password
     **************************************************************************/
    private void setTrustStore(String strTrustStore, String strTrustStorePassword) throws Exception
    {
        if (strTrustStore == null)
        {
            throw new Exception("Setting truststore fail due to null truststore path");
        }
        else if (strTrustStorePassword == null)
        {
            throw new Exception("Setting truststore fail due to null truststore password");
        }
        // set the truststore containing client trusted certificates into system properties.
        System.setProperty("javax.net.ssl.trustStore", strTrustStore);
        System.setProperty("javax.net.ssl.trustStorePassword", strTrustStorePassword);
    }
    /***************************************************************************
     * <p>
     * Set mutual authentication if the remote server required client
     * authentication.
     * </p>
     *
     * @param String
     *            strKeyStore : keystore path
     * @param String
     *            strKeyStorePassword : keystore password
     * @param String
     *            strKeyPassword : key password
     **************************************************************************/
    private void setMutualAuthentication(HttpsURLConnection httpsURLConnection, String strKeyStore,
            String strKeyStorePassword, String strKeyPassword) throws Exception
    {
        SSLContext sslContext = null;
        if (strKeyStore == null)
        {
            throw new Exception("Setting mutual authentication fail due to null keystore path");
        }
        else if (strKeyStorePassword == null)
        {
            throw new Exception("Setting mutual authentication fail due to null keystore password");
        }
        else if (strKeyPassword == null)
        {
            throw new Exception("Setting mutual authentication fail due to null key password");
        }
        try
        {
            sslContext = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, DEFAULT_SSL_PROVIDER);
        }
        catch (Exception e)
        {
            logger.error("HttpsURLConnectionFactory.setMutualAuthentication:Exception - " + e.getMessage());
            throw new Exception("HttpsURLConnectionFactory.setMutualAuthentication fail.", e);
        }
        try
        {
            // Load keystore containing server certificate.
            KeyStore keyStore = KeyStore.getInstance(DEFAULT_KEYSTORE_TYPE);
            char[] chKeyStorePassword = strKeyStorePassword.toCharArray();
            keyStore.load(new FileInputStream(strKeyStore), chKeyStorePassword);
            // Create specific Key Manager for mutual authentication.
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
            char[] chKeyPassword = strKeyPassword.toCharArray();
            keyManagerFactory.init(keyStore, chKeyPassword);
            // Initialize the SSLContext with the created KeyManager.
            sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            // Set the sslSocketFactory into httpsURLConnection.
            httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
        }
        catch (Exception e)
        {
            logger.error("HttpsURLConnectionFactory.setMutualAuthentication:Exception - " + e.getMessage());
            throw new Exception("HttpsURLConnectionFactory.setMutualAuthentication fail.", e);
        }
    }
}
java.lang.Exception: HttpsURLConnectionFactory.openConnection fail.
 at com.pbb.mobile.common.net.HttpsURLConnectionFactory.openConnection(HttpsURLConnectionFactory.java:300)
 at com.pbb.mobile.common.net.HttpsURLConnectionFactory.connect(HttpsURLConnectionFactory.java:317)
 at WSJsonParserServlet.sendJSONToWSServer(WSJsonParserServlet.java:268)
 at WSJsonParserServlet.service(WSJsonParserServlet.java:164)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:915)
 at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:459)
 at org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:180)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:814)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:915)
 at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:398)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:277)
 at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:255)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:586)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:556)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:187)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:586)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:556)
 at com.sun.webserver.connector.nsapi.NSAPIProcessor.service(NSAPIProcessor.java:160)
 Caused by: java.net.SocketException: Connection reset
 at java.net.SocketInputStream.read(SocketInputStream.java:168)
 at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
 at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
 at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
 at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
 at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1014)
 at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
 at com.pbb.mobile.common.net.HttpsURLConnectionFactory.openConnection(HttpsURLConnectionFactory.java:290)
 ... 18 more
 
 Does anyone has any idea what possibly that could cause this error?
 Appreciate very much for the help.
 Thank you!
 
 | 
 |  |  |  |
 
|  |  |  
|  |  | 
 |  | 
 
 发表于 4-8-2014 07:42 PM
|
显示全部楼层 
| It will be quicker if you post this question to stackoverflow. | 
 |  |  |  |
 
|  |  |  
|  |  | 
 |  | 
 
 发表于 26-2-2015 01:30 AM
|
显示全部楼层 
| Handshake error. You were not able to start handshake due to your client certificate must be in the web service server for authentication. | 
 |  |  |  |
 
|  |  |  
|  |  |  |  | 
            本周最热论坛帖子 |