stilz
stilz

Reputation: 113

URLConnection getInputStream blocks thread

I encountered an issue with getInputStream method in URLConnection class. I'm aware there are some other similar issues discussed in other threads, but no single solution seemed to work in my case.

The funny thing is that as first execution goes well, further ones fail (block). Prior to describing the issue I'd like to write some background. Here it is.

Basically I have simple client-server configuration. As I don't want to hardcode server address and port in client app, I employ HTTP server (nginx), from which actual connection parameters can be retrieved.

On the client side, there's a 'network thread', that is controlled by service. Service starts the thread and can interrupt it when needed. At the very beginning of run() method there's invocation of following function:

private ConnectionParameters obtainConnectionParameters(String url) throws MalformedURLException, IOException {
    URLConnection connection = new URL(url).openConnection();
    InputStream in = connection.getInputStream(); // here the problem occurs

    ... // do some processing

    in.close();     
    return connectionParameters;
}

When connection parameters are obtained, another socket connection is opened. After some time thread may be closed or simply reach end of run() method. I double-checked that it exits cleanly.

Returning to the problem, I have no idea what may be causing this to happen. Do you have any clues what can possibly causing this behavior?

I'd also like to mention that service and the network thread are running in separate (background) process from activities. There's no other place in this proces where URLConnection is used. It's worth noticing that all variables used in method obtainConnectionParameters are local.

I suppose that nothing crucial is missing in the description. Otherwise please let me know, so I can edit my post.

EDIT (1):

I have just tried apache HTTP client as in thread Make an HTTP request with android and it worked well. I'd love to find out what is wrong with URLConnection, though.

Upvotes: 2

Views: 2440

Answers (1)

Tom
Tom

Reputation: 1454

If I understand you correctly, the code snippet above is called multiple times, and the first time it works fine, but the second time it blocks on the getInputStream() call?

The problem could be on the server side. Maybe the server is only accepting one connection at a time, and the first connection you made is still open? Is it possible to open the url with a browser multiple times, to verify that the server works as expected?

Upvotes: 1

Related Questions