佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 1046|回复: 2

Web Service Connection Reset Problem

[复制链接]
发表于 4-8-2014 06:35 PM | 显示全部楼层 |阅读模式
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
  1. try
  2.                 {
  3.                         int intStatus;
  4.                         String szResMsg;
  5.                         String szResContent;
  6.                        
  7.                         HttpsURLConnectionFactory factory = new HttpsURLConnectionFactory("https://someuri", "someuri.com.my", path to the truststore", "password for the truststore");                       
  8.                 
  9.                         StringBuffer sbPost = new StringBuffer();
  10.                         sbPost.append(jsonObject.toString());
  11.                        
  12.                 factory.setRequestContent(sbPost.toString().getBytes());
  13.                 factory.setRequestMethod("POST");                
  14.                 factory.setRequestProperty("content-type", "text/json");
  15.                 
  16.                 intStatus = factory.connect();
  17.                         
  18.                 szResMsg = factory.getResponseMessage();
  19.                 szResContent = factory.getResponseContent();                
  20.                 
  21.                 logger.info("reading status: [" + intStatus + "]");
  22.                 logger.info("reading reply msg: [" + szResMsg + "]");
  23.                 logger.info("reading reply content: [" + szResContent + "]");
  24.                 }
  25.                 catch(Exception e)
  26.                 {
  27.                         logger.error("WSJsonParserServlet.sendJSONToWSServer: " + e.getMessage());
  28.                         e.printStackTrace();
  29.                         return false;
  30.                 }
复制代码
The HttpsURLConnectionFactory code
  1. public class HttpsURLConnectionFactory
  2. {
  3.     private static final String DEFAULT_KEYSTORE_TYPE   = "JKS";
  4.     private static final String DEFAULT_ALGORITHM       = "SunX509";
  5.     private static final String DEFAULT_SSL_PROTOCOL    = "TLS";
  6.     private static final String DEFAULT_SSL_PROVIDER    = "SunJSSE";


  7.     private String strURL                               = null;
  8.     private HttpsURLConnection httpsURLConnection       = null;
  9.     private String strTrustedHost                       = null;

  10.     private String strKeyStore                          = null;
  11.     private String strKeyStorePassword                  = null;
  12.     private String strKeyPassword                       = null;

  13.     private boolean bMutualAuth                         = false;
  14.     private boolean bProxyExists                        = false;
  15.     private String strProxyAuthCredential               = null;

  16.     private String strRequestMethod                     = "GET";
  17.     private Hashtable hRequestProperties                = null;

  18.     private int intResponseCode                         = 0;
  19.     private String strResponseContent                   = null;
  20.     private String strResponseMessage                   = null;

  21.     private Hashtable hResponseHeaders                  = new Hashtable();
  22.     private byte[] bContent                             = null;
  23.    
  24.     private String strRequestPropertyKey                = null;
  25.     private String strRequestPropertyValue              = null;

  26.     private PBBLogger logger = PBBLogger.getInstance();


  27.     public HttpsURLConnectionFactory(String strURL)
  28.     {
  29.         this.strURL = strURL;
  30.     }

  31.     public HttpsURLConnectionFactory(String strURL, String strTrustStore, String strTrustStorePassword)
  32.             throws Exception
  33.     {
  34.         this.strURL = strURL;
  35.         setSystemProperties();
  36.         setTrustStore(strTrustStore, strTrustStorePassword);
  37.     }

  38.     public HttpsURLConnectionFactory(String strURL, String strTrustedHost, String strTrustStore,
  39.             String strTrustStorePassword) throws Exception
  40.     {
  41.         this.strURL = strURL;
  42.         this.strTrustedHost = strTrustedHost;
  43.         setSystemProperties();
  44.         setTrustStore(strTrustStore, strTrustStorePassword);
  45.     }

  46.     public HttpsURLConnectionFactory(String strURL, String strTrustStore, String strTrustStorePassword,
  47.             String strKeyStore, String strKeyStorePassword, String strKeyPassword) throws Exception
  48.     {
  49.         this.strURL = strURL;
  50.         this.strKeyStore = strKeyStore;
  51.         this.strKeyStorePassword = strKeyStorePassword;
  52.         this.strKeyPassword = strKeyPassword;
  53.         this.bMutualAuth = true;
  54.         setSystemProperties();
  55.         setTrustStore(strTrustStore, strTrustStorePassword);
  56.     }

  57.     public HttpsURLConnectionFactory(String strURL, String strTrustedHost, String strTrustStore,
  58.             String strTrustStorePassword, String strKeyStore, String strKeyStorePassword, String strKeyPassword)
  59.             throws Exception
  60.     {
  61.         this.strURL = strURL;
  62.         this.strTrustedHost = strTrustedHost;
  63.         this.strKeyStore = strKeyStore;
  64.         this.strKeyStorePassword = strKeyStorePassword;
  65.         this.strKeyPassword = strKeyPassword;
  66.         this.bMutualAuth = true;
  67.         setSystemProperties();
  68.         setTrustStore(strTrustStore, strTrustStorePassword);
  69.     }


  70.     /***************************************************************************
  71.      * <p>
  72.      * Set the system property for proxy.
  73.      * </p>
  74.      *
  75.      * @Param String
  76.      *            strProxyHost : Proxy host to tunnel through
  77.      * @Param String
  78.      *            strProxyPort : Proxy port to tunnel through
  79.      **************************************************************************/
  80.     public void setProxy(String strProxyHost, int intProxyPort)
  81.     {
  82.         System.setProperty("https.proxyHost", strProxyHost);
  83.         System.setProperty("https.proxyPort", String.valueOf(intProxyPort));
  84.         bProxyExists = true;

  85.         logger.info("HttpsURLConnectionFactory.setProxy:Proxy Host is : [" + strProxyHost + "]");
  86.         logger.info("HttpsURLConnectionFactory.setProxy:Proxy Port is : [" + intProxyPort + "]");
  87.     }

  88.     public void addProxyCredential(String strUsername, String strPassword)
  89.     {
  90.         String strUsernamePassword = strUsername + ":" + strPassword;
  91.         strProxyAuthCredential = "Proxy-Authorization: Basic "
  92.                 + new sun.misc.BASE64Encoder().encode(strUsernamePassword.getBytes());

  93.         logger.info("HttpsURLConnectionFactory.addProxyCredential:Proxy Username is :[" + strUsername + "]");
  94.         logger.info("HttpsURLConnectionFactory.addProxyCredential:Proxy Password is :[" + strPassword + "]");
  95.     }

  96.     public void setConnectionTimeout(int intConnectionTimeout)
  97.     {
  98.     }

  99.     public void setRequestMethod(String strRequestMethod)
  100.     {
  101.         this.strRequestMethod = strRequestMethod;
  102.         logger.info("HttpsURLConnectionFactory.setRequestMethod:Request Method is :[" + strRequestMethod + "]");
  103.     }

  104.     public void setRequestProperties(Hashtable hRequestProperties)
  105.     {
  106.         this.hRequestProperties = hRequestProperties;
  107.     }
  108.    
  109.     public void setRequestContent(byte[] bContent)
  110.     {
  111.         this.bContent = bContent;
  112.     }
  113.    
  114.     public void setRequestProperty(String strRequestPropertyKey, String strRequestPropertyValue)
  115.     {
  116.             this.strRequestPropertyKey = strRequestPropertyKey;
  117.             this.strRequestPropertyValue = strRequestPropertyValue;
  118.     }

  119.     public HttpsURLConnection openConnection() throws Exception
  120.     {
  121.         try
  122.         {
  123.             logger.info("HttpsURLConnectionFactory.openConnection:Opening connection...");
  124.             URL url = null;
  125.             try
  126.             {
  127.                 url = new URL(getURL());
  128.             }
  129.             catch (MalformedURLException e)
  130.             {
  131.                 logger.error("HttpsURLConnectionFactory.openConnection:Exception - " + e.getMessage());
  132.                 throw new Exception("HttpsURLConnectionFactory.openConnection:Invalid url address", e);
  133.             }

  134.             HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

  135.             // Host name vs CN in certificate verification.If trusted host is
  136.             // defined, HostNameVerifier will compare
  137.             // trusted host against certificate host name, else host in url will
  138.             // be compared against certificate host name.
  139.             httpsURLConnection.setHostnameVerifier(new TrustedHostVerifier(strTrustedHost));

  140.             // tunnel through proxy
  141.             if (bProxyExists)
  142.             {
  143.                 if (strProxyAuthCredential == null)
  144.                 {
  145.                     httpsURLConnection.setSSLSocketFactory(new SSLTunnelSocketFactory(System
  146.                             .getProperty("https.proxyHost"), System.getProperty("https.proxyPort")));
  147.                 }
  148.                 else
  149.                 {
  150.                     httpsURLConnection.setSSLSocketFactory(new SSLTunnelSocketFactory(System
  151.                             .getProperty("https.proxyHost"), System.getProperty("https.proxyPort"),
  152.                             strProxyAuthCredential));
  153.                 }
  154.             }

  155.             // set mutual authentication if remote peer require client
  156.             // authentication
  157.             if (bMutualAuth)
  158.             {
  159.                 setMutualAuthentication(httpsURLConnection, strKeyStore, strKeyStorePassword, strKeyPassword);
  160.             }

  161.             // setting request method
  162.             try
  163.             {
  164.                 httpsURLConnection.setRequestMethod(strRequestMethod);
  165.             }
  166.             catch (ProtocolException e)
  167.             {
  168.                 throw new Exception("HttpsURLConnectionFactory.openConnection:Set request method fail.", e);
  169.             }

  170.             // setting request property
  171.             if (hRequestProperties != null)
  172.             {
  173.                 for (Enumeration e = hRequestProperties.keys(); e.hasMoreElements();)
  174.                 {
  175.                     String strRequestProperty = (String) e.nextElement();
  176.                     httpsURLConnection.setRequestProperty(strRequestProperty, (String) hRequestProperties
  177.                             .get(strRequestProperty));
  178.                 }
  179.             }
  180.             
  181.             // set single request property
  182.             if(strRequestPropertyKey != null)
  183.             {
  184.                     httpsURLConnection.setRequestProperty(strRequestPropertyKey, strRequestPropertyValue);
  185.             }
  186.             
  187.             httpsURLConnection.setDoInput(true);
  188.             httpsURLConnection.setDoOutput(true);
  189.             httpsURLConnection.setUseCaches(false);
  190.             if (bContent != null)
  191.             {
  192.                 OutputStream out = httpsURLConnection.getOutputStream();
  193.                 out.write(bContent);
  194.                 out.flush();
  195.                 out.close();
  196.             }            
  197.             setConnectionObject(httpsURLConnection);
  198.         }
  199.         catch (IOException e)
  200.         {
  201.             logger.error("HttpsURLConnectionFactory.openConnection:Exception - " + e.getMessage());
  202.             throw new Exception("HttpsURLConnectionFactory.openConnection fail.", e);
  203.         }
  204.         return httpsURLConnection;
  205.     }

  206.     /***************************************************************************
  207.      * <p>
  208.      * Get reply message from remote peer.
  209.      * </p>
  210.      *
  211.      * @return String : Reply message from remote peer
  212.      **************************************************************************/
  213.     public int connect() throws Exception
  214.     {
  215.         HttpsURLConnection httpsURLConnection = getConnectionObject();
  216.         if (httpsURLConnection == null)
  217.         {
  218.             httpsURLConnection = openConnection();
  219.         }

  220.         // Connecting to url
  221.         try
  222.         {
  223.             logger.info("HttpsURLConnectionFactory.connect:Connecting...");
  224.             httpsURLConnection.connect();
  225.         }
  226.         catch (IOException e)
  227.         {
  228.             logger.error("HttpsURLConnectionFactory.connect:Exception - " + e.getMessage());
  229.             throw new Exception("HttpsURLConnectionFactory:fail.", e);
  230.         }

  231.         // Reading reply from remote server
  232.         try
  233.         {
  234.             logger.info("HttpsURLConnectionFactory.connect:Reading reply...");
  235.             intResponseCode = httpsURLConnection.getResponseCode();
  236.             setResponseMessage(httpsURLConnection.getResponseMessage());

  237.             int i=1;
  238.             while (httpsURLConnection.getHeaderField(i) != null)
  239.             {
  240.                 hResponseHeaders.put(httpsURLConnection.getHeaderFieldKey(i).toUpperCase(), httpsURLConnection.getHeaderField(i));
  241.                 i++;
  242.             }

  243.             BufferedReader reader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
  244.             String strResponseContent = new String();
  245.             for (String strTemp = null; (strTemp = reader.readLine()) != null;)
  246.             {
  247.                 strResponseContent += strTemp + "\n";
  248.             }
  249.             if (!strResponseContent.equals(""))
  250.             {
  251.                 strResponseContent = strResponseContent.substring(0, strResponseContent.lastIndexOf("\n"));
  252.             }
  253.             setResponseContent(strResponseContent);
  254.             reader.close();
  255.         }
  256.         catch (IOException e)
  257.         {
  258.             logger.error("HttpsURLConnectionFactory.connect:Exception - " + e.getMessage());
  259.             throw new Exception("HttpsURLConnectionFactory.connect:Fail to get reply from remote peer", e);
  260.         }
  261.         logger.info("HttpsURLConnectionFactory.connect:Disconnecting...");
  262.         httpsURLConnection.disconnect();
  263.         return intResponseCode;
  264.     }

  265.     public void setConnectionObject(HttpsURLConnection httpsURLConnection)
  266.     {
  267.         this.httpsURLConnection = httpsURLConnection;
  268.     }

  269.     public HttpsURLConnection getConnectionObject()
  270.     {
  271.         return this.httpsURLConnection;
  272.     }

  273.     public String getResponseMessage()
  274.     {
  275.         return this.strResponseMessage;
  276.     }

  277.     public String getResponseContent()
  278.     {
  279.         return this.strResponseContent;
  280.     }

  281.     public String getResponseHeader(String strHeader)
  282.     {
  283.         if (hResponseHeaders.containsKey(strHeader))
  284.         {
  285.             return (String)hResponseHeaders.get(strHeader);
  286.         }
  287.         else
  288.         {
  289.             return null;
  290.         }
  291.     }

  292.     private String getURL()
  293.     {
  294.         return this.strURL;
  295.     }

  296.     private void setResponseMessage(String strResponseMessage)
  297.     {
  298.         this.strResponseMessage = strResponseMessage;
  299.     }

  300.     private void setResponseContent(String strResponseContent)
  301.     {
  302.         this.strResponseContent = strResponseContent;
  303.     }

  304.     /***************************************************************************
  305.      * <p>
  306.      * Set the related system properties values.
  307.      * </p>
  308.      **************************************************************************/
  309.     private void setSystemProperties()
  310.     {
  311.         System.setProperty("javax.net.debug", "all");
  312.         //System.setProperty("https.protocols", "TLSv1");

  313.         // provider
  314.         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  315.         System.setProperty("java.protocol.handler.pkgs","javax.net.ssl");
  316.     }

  317.     /***************************************************************************
  318.      * <p>
  319.      * Set truststore properties into system properties.
  320.      * </p>
  321.      *
  322.      * @param String
  323.      *            strtTrustStore : Truststore path
  324.      * @param String
  325.      *            strTrustStorePassword : Truststore password
  326.      **************************************************************************/
  327.     private void setTrustStore(String strTrustStore, String strTrustStorePassword) throws Exception
  328.     {
  329.         if (strTrustStore == null)
  330.         {
  331.             throw new Exception("Setting truststore fail due to null truststore path");
  332.         }
  333.         else if (strTrustStorePassword == null)
  334.         {
  335.             throw new Exception("Setting truststore fail due to null truststore password");
  336.         }

  337.         // set the truststore containing client trusted certificates into system properties.
  338.         System.setProperty("javax.net.ssl.trustStore", strTrustStore);
  339.         System.setProperty("javax.net.ssl.trustStorePassword", strTrustStorePassword);
  340.     }

  341.     /***************************************************************************
  342.      * <p>
  343.      * Set mutual authentication if the remote server required client
  344.      * authentication.
  345.      * </p>
  346.      *
  347.      * @param String
  348.      *            strKeyStore : keystore path
  349.      * @param String
  350.      *            strKeyStorePassword : keystore password
  351.      * @param String
  352.      *            strKeyPassword : key password
  353.      **************************************************************************/
  354.     private void setMutualAuthentication(HttpsURLConnection httpsURLConnection, String strKeyStore,
  355.             String strKeyStorePassword, String strKeyPassword) throws Exception
  356.     {
  357.         SSLContext sslContext = null;
  358.         if (strKeyStore == null)
  359.         {
  360.             throw new Exception("Setting mutual authentication fail due to null keystore path");
  361.         }
  362.         else if (strKeyStorePassword == null)
  363.         {
  364.             throw new Exception("Setting mutual authentication fail due to null keystore password");
  365.         }
  366.         else if (strKeyPassword == null)
  367.         {
  368.             throw new Exception("Setting mutual authentication fail due to null key password");
  369.         }

  370.         try
  371.         {
  372.             sslContext = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, DEFAULT_SSL_PROVIDER);

  373.         }
  374.         catch (Exception e)
  375.         {
  376.             logger.error("HttpsURLConnectionFactory.setMutualAuthentication:Exception - " + e.getMessage());
  377.             throw new Exception("HttpsURLConnectionFactory.setMutualAuthentication fail.", e);
  378.         }

  379.         try
  380.         {
  381.             // Load keystore containing server certificate.
  382.             KeyStore keyStore = KeyStore.getInstance(DEFAULT_KEYSTORE_TYPE);
  383.             char[] chKeyStorePassword = strKeyStorePassword.toCharArray();
  384.             keyStore.load(new FileInputStream(strKeyStore), chKeyStorePassword);

  385.             // Create specific Key Manager for mutual authentication.
  386.             KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
  387.             char[] chKeyPassword = strKeyPassword.toCharArray();
  388.             keyManagerFactory.init(keyStore, chKeyPassword);

  389.             // Initialize the SSLContext with the created KeyManager.
  390.             sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
  391.             SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

  392.             // Set the sslSocketFactory into httpsURLConnection.
  393.             httpsURLConnection.setSSLSocketFactory(sslSocketFactory);

  394.         }
  395.         catch (Exception e)
  396.         {
  397.             logger.error("HttpsURLConnectionFactory.setMutualAuthentication:Exception - " + e.getMessage());
  398.             throw new Exception("HttpsURLConnectionFactory.setMutualAuthentication fail.", e);
  399.         }
  400.     }
  401. }
复制代码
and the error returned
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!
回复

使用道具 举报


ADVERTISEMENT

发表于 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.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 29-3-2024 07:54 PM , Processed in 0.069751 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表