You cannot use java.net.URLConnection in this case, because URLConnection doesnot support timeouts.
The solution is to use the Open source Jakarta Commons HttpClient API.
This is a robust API in terms of functionalities including cookie handling, secure communication(SSL), various authentication mechanisms, connection over a proxy etc.
It implements HTTP 1.0 and 1.1 and supports all HTTP methods.
Here is a sample code that submits a form data over a Post method, and prints the response. Instead of waiting indefenitely, the request will timeout after waiting for response after 10 seconds.
package jims;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
import java.net.SocketTimeoutException;
public class TimeOutTest {
private static String url = "http://localhost:8091/Classic/login.do";
public static void main(String[] args) {
//Instantiate the HttpClient and PostMethod
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
//or GetMethod(url) as the case may be
try {
//Sets the Retry Handler. This will try to resend the request upto 3 times.
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
//Sets the Timeout value - in milliseconds
method.getParams().setSoTimeout(10000);
//Sets the form data - Key value Pairs
NameValuePair form_data [] = new NameValuePair[3];
form_data [0]= new NameValuePair("userId","yyyyy");
form_data [1]= new NameValuePair("password","xxxxxx");
form_data [2]= new NameValuePair("userRole","ZZZZZ");
method.setQueryString(form_data);
//Execute the Method
System.out.println("START:"+System.currentTimeMillis());
//Check the Response Code and print response
int statusCode = client.executeMethod(method);
if (statusCode != 200) //SC_OK
{
System.err.println("Error Occurred: " + method.getStatusLine());
}
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
}
catch (HttpException e)
{
System.err.println("Fatal protocol violation: " + e.getMessage());
}
catch (SocketTimeoutException e)
{
System.err.println("Request Timed Out!");
System.out.println("END:"+System.currentTimeMillis());
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
//Finally, release the Connection
method.releaseConnection();
}
}
}
Please note that the socket timeout can be set at multiple layers of the request. It can be set at the method level(which we just experimented). It can also be set at the Connection level and the ConnectionManager level. Refer the Apache Commons HttpClient API Documentation for more information.
You need to have commons-httpclient-3.1.jar added to your classpath before running this example. Download the ZIP file, extract the jar and add it in the classpath.
You might have to download and add to classpath Apache Commons Logging and Commons Codec Jars if they are not there already, as the HttpClient API has dependancy on these two.
No comments:
Post a Comment