8

I have searched a lot for this exception, which rarelly occur, but I didn't find any relevant answer which can solve my problem, I am using HttpURLConnection to get response as a xml from a url, it works fine but sometimes i get this exception:
java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer), I have used following code and url1 is my url which gives a xml.

url=new URL(url1);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);  
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result, line = reader.readLine();
result = line;
           while((line=reader.readLine())!=null)
                       {
               result+=line;
           }

           System.out.println("Result: "+result);
Dediqated
  • 901
  • 15
  • 35
OM Yadav
  • 81
  • 1
  • 1
  • 2
  • have a connection time out http://stackoverflow.com/questions/11638634/android-how-to-set-a-http-connection-timeout-and-react-to-it – Raghunandan May 11 '13 at 04:31
  • possible duplicate of [Getting "SocketException : Connection reset by peer" in Android](http://stackoverflow.com/questions/11207394/getting-socketexception-connection-reset-by-peer-in-android) – Jim G. Apr 09 '14 at 02:09

4 Answers4

10

Try put urlConnection.setRequestProperty("connection", "close"); before connecting. This will disable keep-alive property which is on by default

stuckedunderflow
  • 3,551
  • 8
  • 46
  • 63
2

I had a similar problem when trying to talk with my server. I'm still not sure what happened, but I found this in my search to resolve the issue:

ok, the answer was that it's the server's fault - it had to close the connection after each request . it might be that android keeps a pool of connections and use the old one or something like that . anyway , now it works.

After reading this post, I killed the apache instance running on my server, let the phone see that the connection was refused, and restarted apache. After that, the issue disappeared. Hope this helps!

Dylan Knowles
  • 2,726
  • 1
  • 26
  • 52
0

In my case i changed from http to https and everything became normal

Marriage
  • 501
  • 3
  • 15
-1

open your browser you are using and try copying the urland paste it into your browser of your MOBILE DEVICE , if you still get the same error or may be connection refused that means your MOBILE and YOUR PC on which server runs are not on the same plan.

Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
  • Yes I did this thing but it is opening in browser of mobile, as i explained it is occuring 5 times out of 20 times tested. – OM Yadav May 11 '13 at 04:44
  • No it doesn't. There can't be a connection to reset unless there was a connection, and there can't be a connection unless there was a network path between the peers. – user207421 May 17 '17 at 07:28