A_Elric
A_Elric

Reputation: 3568

Handling HttpClient (Httpget) timeouts

So I'm running a multithreaded program that makes a bunch of calls to api's and a few web-pages that it wants to scrape. In some unusual cases the httpget will fail horribly and will cause the program to 'freeze' (the thread never exits, the threadpool never closes,main never exits, etc.)

I need to set a timeout to the http connections that I'm making. I'm using a DefaultHttpClient

DefaultHttpClient httpclient = new DefaultHttpClient();

and I'm not setting any params.

Can someone help me time these out or at least point me to where I should be looking for handling timeouts? (Apache seems to have great libs that never seem to have good examples around)

Upvotes: 1

Views: 3498

Answers (3)

Yogendra Singh
Yogendra Singh

Reputation: 34367

You may want to use one of the two, preferably the first.

 HttpConnectionParams.setConnectionTimeout(int) 

 HttpConnection.setConnectionTimeout(int)

as:

 HttpConnectionParams.setConnectionTimeout( httpParams, 5000 );

Upvotes: 0

Rajamanickem
Rajamanickem

Reputation: 162

Try something as shown below.

int connectiontimeout = 1000; //1 second
int sockettimeout = 1000;

HttpParams httpparameters = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpparameters, connectiontimeout);
HttpConnectionParams.setSoTimeout(httpparameters, sockettimeout);

HttpClient httpclient = new DefaultHttpClient(httpparameters);

Upvotes: 6

Brian Agnew
Brian Agnew

Reputation: 272207

You want the HttpConnectionParams. You will likely need to distinguish between the connection timeout, and the socket time out (which relates to reads, not connections)

SO_TIMEOUT Defines the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.

CONNECTION_TIMEOUT Determines the timeout until a connection is etablished.

See here for more detail re. these options.

Upvotes: 1

Related Questions