Rectangle 27 9

I'd recommend disabling the http.keepalive system property. The performance section of the documentation indicates that socket connections will be reused when possible. It sounds like it is trying to reuse the connection, but the proxy has already closed it. On this post, Darrell also indicates that changing the system property solved his problem.

System.setProperty("http.keepAlive", "false");

I agree that reusing the connections would be better. Have you made sure that the InputStream you get from the connection is closed after being used?

If I close the input stream I will be releasing all the resources held by the stream including the underlying socket. So connection cannot be reused in that case.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 6

Turns out they've fixed this issue in Android on Jan 8th [1]. The fix basically marks the old connection as recycled and internally retries the request.

To fix this for now, I would suggest retrying requests if an EOFException is encountered with a retry limit to prevent stackoverlows.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 4

I had this problem with normal HTTP connections as well. The first request went OK, the second failed with an EOFException.

urlConnection.setChunkedStreamingMode(0);

I could be that the webserver I'm calling can't handle chuncked data well. Don't know.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 2

Actually the url was not well formed. Hence I was getting EOFException. I was sending Base64 data in url and while converting the data into Base64 I was not giving NO_WRAP flag. Becasue of that the Base64 data was not coming in single long line.

Android: HttpURLConnection throwing EOFException - Stack Overflow

android android-asynctask httpurlconnection eofexception
Rectangle 27 0

I had this problem with normal HTTP connections as well. The first request went OK, the second failed with an EOFException.

urlConnection.setChunkedStreamingMode(0);

I could be that the webserver I'm calling can't handle chuncked data well. Don't know.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 0

You can use this method to pick data from server then you convert the inputs trim to string then you can parse for further use.`

public static InputStream getUrlData(final String url)
        throws URISyntaxException, ClientProtocolException, IOException {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpGet method = new HttpGet(new URI(url));
    final HttpResponse res = client.execute(method);
    return res.getEntity().getContent();
    }

HttpClient is buggy and very slow (and effectively deprecated.)

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 0

I suspect it might be the server that is at fault here, and the HttpURLConnection is not as forgiving as other implementations. That was the cause of my EOFException. I suspect in my case this would not be intermittent (fixed it before testing the N retry workaround), so the answers above relate to other issues and be a correct solution in those cases.

My server was using python SimpleHTTPServer and I was wrongly assuming all I needed to do to indicate success was the following:

self.send_response(200)

That sends the initial response header line, a server and a date header, but leaves the stream in the state where you are able to send additional headers too. HTTP requires an additional new line after headers to indicate they are finished. It appears if this new line isn't present when you attempt to get the result body InputStream or response code etc with HttpURLConnection then it throws the EOFException (which is actually reasonable, thinking about it). Some HTTP clients did accept the short response and reported the success result code which lead to me perhaps unfairly pointing the finger at HttpURLConnection.

self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()

Android HttpUrlConnection EOFException - Stack Overflow

android httpurlconnection
Rectangle 27 0

That EOFException suggests the response is malformed - perhaps lacking a blank line after the headers. Some HTTP client code is more forgiving in that case, for me iOS could handle my server responses fine but I was getting EOFException on Android using HttpURLConnection.

My server was using python SimpleHTTPServer and I was wrongly assuming all I needed to do to indicate success was the following:

self.send_response(200)

That sends the initial response header line, a server and a date header, but leaves the stream in the state where you are able to send additional headers too. HTTP requires an additional new line after headers to indicate they are finished. It appears if this new line isn't present when you attempt to get the result body InputStream or response code etc with HttpURLConnection then it throws the EOFException (which is actually reasonable, thinking about it). Some HTTP clients did accept the short response and reported the success result code which lead to me perhaps unfairly pointing the finger at HttpURLConnection.

self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()

No more EOFException with that code. It's possible the "Connection: close" solutions trigger some behaviour on certain servers that might work around this (eg ensuring the response is valid before closing) but that wasn't the case with the python SimpleHTTPServer, and the root cause turned out to be my fault.

NB: There are some bugs on Android pre-Froyo (2.2) relating to keep-alive connections - see the blog post here: http://android-developers.blogspot.co.uk/2011/09/androids-http-clients.html. I'm yet to see convincing evidence of bugs with newer versions of Android.

android - HttpsUrlConnection EOFException - Stack Overflow

android httpurlconnection eofexception httpsurlconnection
Rectangle 27 0

First, check whether your URL contains unexpected newline ('\n' or '\r\n'), if does, you will get EOFException when reading response. The newline will trunk HTTP packages and server thinks client has more data to send, so there is no response. Every attempt to read response will get EOF immediately.

httpurlconnection - Android HttpsUrlConnection eofexception - Stack Ov...

android httpurlconnection eofexception
Rectangle 27 0

I checked conn.getResponseCode() and get a 403. The exception might be due to that.

android - EOFException and FileNotFoundException in HttpURLConnection ...

android httpurlconnection filenotfoundexception eofexception
Rectangle 27 0

Make sure you close off the connection before your recursive call.

Also, I added the following to the connection to close the connection, though I'm not sure if it helps:

if (retries > 0) {
    connection.setRequestProperty("Connection", "close");
}

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 0

public ResponseObject sendPOST(String urlPrefix, JSONObject payload) throws JSONException {
    String line;
    StringBuffer jsonString = new StringBuffer();
    ResponseObject response = new ResponseObject();
    try {

        URL url = new URL(POST_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        OutputStream os = connection.getOutputStream();
        os.write(payload.toString().getBytes("UTF-8"));
        os.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        response.setResponseMessage(connection.getResponseMessage());
        response.setResponseReturnCode(connection.getResponseCode());
        br.close();
        connection.disconnect();
    } catch (Exception e) {
        Log.w("Exception ",e);
        return response;
    }
    String json = jsonString.toString();
    response.setResponseJsonString(json);
    return response;
}

Android HttpUrlConnection EOFException - Stack Overflow

android httpurlconnection
Rectangle 27 0

I suspect it might be the server that is at fault here, and the HttpURLConnection is not as forgiving as other implementations. That was the cause of my EOFException. I suspect in my case this would not be intermittent (fixed it before testing the N retry workaround), so the answers above relate to other issues and be a correct solution in those cases.

My server was using python SimpleHTTPServer and I was wrongly assuming all I needed to do to indicate success was the following:

self.send_response(200)

That sends the initial response header line, a server and a date header, but leaves the stream in the state where you are able to send additional headers too. HTTP requires an additional new line after headers to indicate they are finished. It appears if this new line isn't present when you attempt to get the result body InputStream or response code etc with HttpURLConnection then it throws the EOFException (which is actually reasonable, thinking about it). Some HTTP clients did accept the short response and reported the success result code which lead to me perhaps unfairly pointing the finger at HttpURLConnection.

self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()

Android HttpUrlConnection EOFException - Stack Overflow

android httpurlconnection
Rectangle 27 0

First, check whether your URL contains unexpected newline ('\n' or '\r\n'), if does, you will get EOFException when reading response. The newline will trunk HTTP packages and server thinks client has more data to send, so there is no response. Every attempt to read response will get EOF immediately.

httpurlconnection - Android HttpsUrlConnection eofexception - Stack Ov...

android httpurlconnection eofexception
Rectangle 27 0

Our conclusion is that there is an issue in the Android platform. Our workaround was to catch the EOFException and retry the request N number of times. Below is the pseudo code:

private static final int MAX_RETRIES = 3;

private ResponseType fetchResult(RequestType request) {
    return fetchResult(request, 0);
}

private ResponseType fetchResult(RequestType request, int reentryCount) {
    try {
        // attempt to execute request
    } catch (EOFException e) {
        if (reentryCount < MAX_RETRIES) {
            fetchResult(request, reentryCount + 1);
        }
    }
    // continue processing response
}

Hi Matt. I am trying this but it is not working. I want to verify that your pseudo code is as follows: 1. open connection via url.openConnection(). 2. If I get a EOF when calling getResponseCode(), then disconnect, set HttpURLConnection to null and connect again. 3. Try this until max number of retries. Is this what you did? Thank you.

Yes, each time you try the request I would advise you to recreate the HttpURLConnection, don't try to reuse the same instance. When you say it is not working what do you mean?

Thanks for answering. I meant I tried doing as you said and I am still having problems with EOFException.

Can you post more details on what problems you are having. Do you just repeatedly get an EOFException no matter how many times you try it? What device(s)/versions of Android are you testing on?

It is working now without code change, weird... But now my SSL Engine is crapping out. Different issue, but thanks for the help.

Android HttpUrlConnection EOFException - Stack Overflow

android httpurlconnection
Rectangle 27 0

if(postData != null){
                byte[] requestContent = getQuery(postData);
                conn.setDoOutput(true);
// Specify content type
                conn.setRequestProperty("Content-Type", mRequestContentType);
                conn.setRequestProperty("Content-Length",
                    Integer.toString(requestContent.length));
                conn.setFixedLengthStreamingMode(requestContent.length);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
                writer.write(requestContent);
                writer.close();
                os.close();
            }

android - EOFException and FileNotFoundException in HttpURLConnection ...

android httpurlconnection filenotfoundexception eofexception
Rectangle 27 0

I'd recommend disabling the http.keepalive system property. The performance section of the documentation indicates that socket connections will be reused when possible. It sounds like it is trying to reuse the connection, but the proxy has already closed it. On this post, Darrell also indicates that changing the system property solved his problem.

System.setProperty("http.keepAlive", "false");

I agree that reusing the connections would be better. Have you made sure that the InputStream you get from the connection is closed after being used?

If I close the input stream I will be releasing all the resources held by the stream including the underlying socket. So connection cannot be reused in that case.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 0

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is),
            8192);
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append((line + "\n"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();

}`

This is exactly what I'm doing in there.

The first time i'm connecting everything's fine. When I do it the second time, it says EOFException on conn.connect(). And this happens only if I hve set a proxy at the device level.

Android HttpURLConnection throwing EOFException - Stack Overflow

android httpurlconnection eofexception
Rectangle 27 0

It appears in some of the newer versions of android, there is a bug with recycled url connections. To fix this (although there may be some performance issues), I needed to add:

if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) { urlConnect.setRequestProperty("Connection", "close"); }

Turned out this is a known bug in Android's class implementation. Calling Connection.setRequestProperty( "Accept-Encoding", "" ); before connecting can be used as workaround.

I copied your code but the issue still persists. I think the issue is somewhere else.

I even tried setting Accept-Encoding but I am still stuck

Android: HttpURLConnection throwing EOFException - Stack Overflow

android android-asynctask httpurlconnection eofexception