java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer) is occuring some times

OM Yadav picture OM Yadav · May 11, 2013 · Viewed 30.7k times · Source

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);

Answer

stuckedoverflow picture stuckedoverflow · Feb 7, 2014

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