friends,
I'm开发者_运维技巧 running into an issue when i try to call webservice and the server/internet is not available. It appears that the connection is taking a long time to timeout
can i set timout manually to show error messgage to user?
any help would be appreciated.
You can try to do it this way:
URL url;
URLConnection connection;
try {
url = new URL("http://foo.bar.com");
connection = url.openConnection();
connection.setConnectTimeout(3000); // set 3 seconds for timeout
connection.connect();
}catch(SocketTimeoutException ss){
// show message to the user
}
There are two kinds of timeout:
- Connection Timeout
that is the time until a connection is established
- Socket Timeout
that is the timeout for waiting for data to be received, setting any of them to 0 means infinite timeout, and it's the default value of both, setting one of them doesn't affect the other.
try{
BasicHttpParams httpParams = new BasicHttpParams();
//this will set socket timeout
HttpConnectionParams.setSoTimeout(httpParams, /*say*/ 3000);
//this will set connection timeout
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
client = new DefaultHttpClient(httpParams);
String url = "some-url";
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
//here use the received response
}
catch(ConnectTimeoutException ex) {
//handle connection timeout here
}
catch(SocketTimeoutException ex) {
//handle socket timeout here
}
Set up your HttpClient this way.
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, connectionTimeoutInMs);
httpClient = new DefaultHttpClient(httpParams);
This will work always...
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, Constants.CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, Constants.SOCKET_CONN_TIMEOUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
url = "write-your-web-url-here";
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity`enter code here`();
if(entity != null) is = entity.getContent();
}catch(ConnectTimeoutException timeoutException) {
System.out.println("ConnectTimeoutException Occured...");
}catch(SocketTimeoutException socketTimeoutException) {
System.out.println("SocketTimeoutException Occured...")
}catch(Exception e){
System.out.println("Exception Occured...");
}
精彩评论