Getting “SocketException : Connection reset by peer” in Android

泪湿孤枕 提交于 2019-11-26 15:14:28
android developer

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.


EDIT: according to the API of HttpURLConnection, this can be solved on the client side too:

The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with BufferedInputStream or BufferedOutputStream. Callers that do only bulk reads or writes may omit buffering. When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string).

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held.

Taken from: developer.android.com/reference/java/net/HttpURLConnection.html

Try to set this property for your HttpURLConnection before connecting:

conn.setRequestProperty("connection", "close");

This will disable "keep-alive" property which is on by default.

This is an old thread i know. But this might help someone.

In my case this error was caused by the .NET WCF (soap) service. One of the objects in the returning result had a DataMember with get{} property but no set{} property.

For serialization to occur every DataMember should have both get{} & set{} available. I implemented an empty set{} (empty due to my business rules), and problem was solved.

My scenerio is a specific bad server implementation, but maybe it'll help someone saving time when troubleshooting.

I was having a lot of these Connection reset by peer when I was visiting certain web pages or downloading files (from my app or the Android browser).

Turned out it was my 3G carrier that blocked the connections (e.g. downloading an .exe file was forbidden).

Do you have the same problem on Wifi ?

in my situation the problem has been solved by cleaning the proxy address and port from APN which was produced by the operator. as I have tested, using IP address of remote server instead of domain name also can solve the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!