how to implement request timeout in android? - android

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...");
}

Related

get the HTTP status server

Hi I am developing an android application, I like to create a class to get the HTTP status before send the data to the server with HTTP Post.
Have any form to get the HTTP status of this server?
I read to get the 200 code is the server is running and another code no
Thanks.
Resolved the timeout is very long, My solution is:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpclient = new DefaultHttpClient(params);
and then:
HttpGet httpRequest = new HttpGet(server);
HttpResponse response = httpclient.execute(httpRequest);
You could do the following
HttpGet httpRequest = new HttpGet(myUri);
HttpEntity httpEntity = null;
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpRequest);
response.getStatusLine().getStatusCode()
This is how you get Response code if you are using HttpUrlConnection :
when server is not running
int status = ((HttpURLConnection) connection).getResponseCode();
Log.i("", "Status : " + status);
And here is if you are using HttpClient :
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());

Android: Is there a way to set a timeout for response = httpclient.execute(httppost);

I'm trying to load information over the network on a thread. When there is no internet it will freeze for a long time before setting off a exception or just freeze.
Is there a way to set a timeout for // FREEZES HERE or takes a long time to through exception when there is no internet?
Is their a way to set a timeout for response = httpclient.execute(httppost);?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://besttechsolutions.biz/projects/bookclub/getevents.php");
// FREEZES HERE or takes a long time to through exception when there is no internet
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
Try the following.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
if(null == httpClient)
httpClient = new DefaultHttpClient(httpParameters);
The above code generally sets a default timeout for httpClient. To check internet access, refer the link posted by Nomand.

Execute a HTTP request within an app

I was wondering if I could make it open But NOT open the android browser, I just need it to visit: (pretend this is the ip) http;//91.91.91.91:2228?1, where it will trigger action on my arduino mega. I have tried to get it just to do this with this code
onclick(Intent websiteIntent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("http;//91.9.91.91:?1");
websiteIntent.setData(uri);
startActivity(websiteIntent);)
but I don't know how to get it to do so
A HttpClient will allow you to call an arbitrary URL within your app:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http;//91.9.91.91:?1");
HttpResponse response = client.execute(request);
Don't forget to wrap in a try catch though.
edit:
new Thread(){
public void run(){
try{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http;//91.9.91.91:?1");
HttpResponse response = client.execute(request);
}catch(Exception e){
// Handle the exception
e.printStackTrace();
}
}
};

Android:Trying to make an httpPost Request but keep getting connection timeout

I am really in pain right now please help me solve this issue.
I've previously also tried to make the http request to my localhost and it all works fine but right now it is not working and I don't know why.
I am trying to make the request from the following code.
HttpClient httpclient = new DefaultHttpClient();
String result="";
try
{
HttpPost httppost = new HttpPost("http://[ip]/php/untitled.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",this.userEmail));
nameValuePairs.add(new BasicNameValuePair("pwd",this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
if(entity!=null)
{
InputStream inputStream=entity.getContent();
result= convertStreamToString(inputStream);
}
}
catch (ClientProtocolException e)
{
Log.e("errorhai",e.getMessage());
}
catch (IOException e)
{
Log.e("errorhai",e.getMessage());
}
return result;
I've also added the internet permission but still it keeps saying
Connect to [ip] timed out.
When I enter the url in my browser it works fine but it is not working here.Please tell me what can be the causes of this problem ?
you can set the time out parameter to handle such type of exception :
HttpParams httpParameters = new BasicHttpParams();
/* Set the timeout in milliseconds until a connection is established.
The default value is zero, that means the timeout is not used.*/
int timeoutConnection = 60*1000*1;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
/* Set the default socket timeout (SO_TIMEOUT)
in milliseconds which is the timeout for waiting for data. */
int timeoutSocket = 60*1000*1;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
//HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
/** Finally, we send our request using HTTP. This is the synchronous
long operation that we need to run on this thread. */
httpResponse = client.execute(request);
/*int responseCode = httpResponse.getStatusLine().getStatusCode();
String message = httpResponse.getStatusLine().getReasonPhrase();*/
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String res = convertStreamToString(instream);
MLog.v("HTTP RESPONSE : ", "Res :-"+res);
if(!res.trim().equalsIgnoreCase("[]")){
response.setResult(res);
response.setSuccess(true);
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.RECORD_NOT_FOUND);
}
/** Closing the input stream will trigger connection release */
instream.close();
}else{
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
}
catch (Exception e) {
//client.getConnectionManager().shutdown();
e.printStackTrace();
response.setSuccess(false);
response.setErrorMessage(AppConstant.NETWORK_ERROR);
}
//you can again try to send request , if your response is not sucess.
//retryHttpRequestIfNotSucess();
your problem might be related to the login. Is your script expecting a preemptive authetification? Do you have a error page for a failed login?
For requesting a page with preemptive http basic authentication i'm using the following code that is working. Have a try, if its working for you too.
DefaultHttpClient httpclient = null;
HttpParams params = new BasicHttpParams();
HttpResponse response = null;
HttpEntity entity = null;
// Set connection parameter
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
httpclient = new DefaultHttpClient(params);
// Create a post statement
HttpPost httppost = new HttpPost(Constants.urlLogin);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);
httppost.getParams().setParameter("http.protocol.single-cookie-header", true);
httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("login_name", this.username));
nvps.add(new BasicNameValuePair("login_passwd", this.userpassword));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httppost);
entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String loadedContent = null;
if (entity != null)
{
loadedContent = EntityUtils.toString(entity, HTTP.UTF_8);
// loadedContent =
// Helper.convertStreamToString(entity.getContent());
entity.consumeContent();
}
if (statusCode != (HttpStatus.SC_OK))
{
throw new ServerCommunicationErrorException();
} else if (!loadedContent.contains("Logout"))
{
// Login failed
throw new LoginFailedException();
}
As you can see, i get a "not logged in" page as result, if the login fails to determine the login process. Further more i set some parameters, that might be also interesting for you. You can look here for more information on parameters.

Difference between URLConnection getInputStream() & HttpEntity getContent()

I try to download pic from the specific url, firstly I use this way to get InputStream:
if (url != null) {
URLConnection ucon = null;
try {
ucon = url.openConnection();
} catch (IOException e2) {
e2.printStackTrace();
}
if (ucon != null) {
ucon.setConnectTimeout(CONN_TIMEOUT);
ucon.setReadTimeout(READ_TIMEOUT);
try {
is = ucon.getInputStream();
It works good, but when I try to download pic from http://111.12.12.232/images/face/bigface/339.gif
I can't get the InputStream, but try to use :
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, false);
HttpConnectionParams.setConnectionTimeout(params, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
HttpGet getRequest;
try {
getRequest = new HttpGet(url.toURI());
HttpClient client = new DefaultHttpClient(params);
HttpResponse response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
This way can get InputStream successfully, and can download the gif.
So I wonder what's the different between the two methods?
Thanks~
It looks like the server returns the image content but also returns a 404 response code, which indicates an error fulfilling the request.
On the 1.6 Sun/Oracle JDK, the HttpURLConnection seems to fail with an IOException when it notices a return code like this, and does not attempt to return content. My guess is that the Android platform has this same behavior, and the Apache HttpClient library you used is a bit more robust to server misconfigurations.

Categories

Resources