Httpurlconnection.Openconnection Fails Second Time

HttpUrlConnection.openConnection fails second time

I solved the problem. Here I leave you the code, in case it might be helpful for someone. Basically I see a trend on Google for using HttpClient/HttpGet instead of HttpUrlConnection. So I tried with those classes, and everything worked:

final HttpClient client = new DefaultHttpClient();
final HttpGet conn = new HttpGet(mURL.toString());

OAuthConsumer consumer = mOAuthManager.getPostConsumer();
consumer.sign(conn);
HttpResponse response = client.execute(conn);
InputSource is = new InputSource(response.getEntity().getContent());

HttpURLConnection request being hit twice to the server for downloading file

Your error lies in this line:

url.openStream()

If we go to grepcode to sources of this function, then we will see:

public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}

But you already opened connection, so you opening connection twice.

As solution you need to replace url.openStream() with connection.getInputStream()

Thus your snipped will looks like:

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
Log.d("File Download", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(connection.getInputStream());

HttpUrlConnection connection reset error when sending second message

At the end it resulted to be a firewall problem with the client and the server. It was blocking the connection for every other time after the first one.

Sometimes HttpURLConnection.getInputStream executes too slowly

'We had a similar issue which is caused by buggy keep-alive in old Java. Add this before connect to see if it helps,

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

or

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


Related Topics



Leave a reply



Submit