简体   繁体   中英

SocketException when connecting to HttpURLConnection after accessing HttpsURLConnection

I have a function which uses an HttpUrlConnection to call up a service on a remote client. This function works fine, until we added a new secure remote client which can only be called using HttpsUrlConnection.

Calling the new https remote client works fine, after calling the new client, the old client will return a java.net.SocketException: Connection reset when trying to get the InputStream object.

My code look something like this:

conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
out = conn.getOutputStream();
writer = new OutputStreamWriter(out);
writer.write(strJson);
writer.close();
in = conn.getInputStream();  // connection reset error here.
reader = new InputStreamReader(in);
rd = new BufferedReader(reader);
while ((line = rd.readLine()) != null) {
    result += line;
}
rd.close();
in.close();
reader.close();
out.close();
conn.disconnect();

Anyone have a clue what happened? Thank you in advance.

The stack trace is like so:

java.net.SocketException: Connection reset 
   at java.net.SocketInputStream.read(SocketInputStream.java:196)
   at java.net.SocketInputStream.read(SocketInputStream.java:122)
   at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
   at sun.security.ssl.InputRecord.read(InputRecord.java:480)
   at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:934)
   at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:891)
   at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
   at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
   at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
   at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
   at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:690)
   at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
   at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:661)
   at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1324)
   at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)

I still don't know what caused the error to happen. My solution is just to not use the java.net.HttpURLConnection, and use org.apache.http.impl.client.DefaultHttpClient instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM