I want my device to give up the http connexion after 5 seconds.
But my code does not work... I never get any timeout message when shutting network down.
Just like if the device still tries to connect, despite de timeout...
Have an idea?
Am I trying to catch the right exception?
Thanks.
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() < 400)
{
... //data processing
}
else
{
errorMsgId = R.string.http_site_error;
}
}
catch (ConnectTimeoutException e)
{
Toast.makeText(this, "Network timeout reached!", Toast.LENGTH_SHORT).show();
Log.e("+++++++++++++++++ ","Network timeout reached!");
}
ok, GOT IT, so in case this could help someone else:
HttpClient httpclient = new DefaultHttpClient();
final HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
You can use something like this:
/**
* Check availability of web service
*
* #param host Address of host
* #param seconds Timeout in seconds
* #return Availability of host
*/
public static boolean checkIfURLExists(String host, int seconds)
{
HttpURLConnection httpUrlConn;
try
{
httpUrlConn = (HttpURLConnection) new URL(host).openConnection();
// Set timeouts in milliseconds
httpUrlConn.setConnectTimeout(seconds * 1000);
httpUrlConn.setReadTimeout(seconds * 1000);
// Print HTTP status code/message for your information.
System.out.println("Response Code: " + httpUrlConn.getResponseCode());
System.out.println("Response Message: "
+ httpUrlConn.getResponseMessage());
return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
return false;
}
}
Perhaps I'm missing something, but where are you associating the parameters that you set the timeout in with the HttpClient that you have created? Shouldn't you do something like this:
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
...
HttpClient httpclient = new DefaultHttpClient(httpParameters);
Related
I am developing an app which send request to server using DefaultHttpClient.I am sending request with GET method.if the port number is wrong then i get connection timeout exception.I have used handler for the exception & return a value when exception occurs. But the sad part is Post Execute is called after 60 seconds.
protected String doInBackground(String... url)
{
HttpURLConnection con = null;
HttpGet httpGet = null;
DefaultHttpClient httpClient=null;
try
{
httpGet = new HttpGet(url[0]);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 5000;
int sockettimeout=5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, sockettimeout);
httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(httpGet );
int code=httpResponse.getStatusLine().getStatusCode();
}
catch (IOException e)
{
if(e.toString().contains("org.apache.http.conn.ConnectTimeoutException"))
{
Log.i("RAE", "Connection Timeedout");
httpClient.getConnectionManager().closeExpiredConnections();
httpClient.getConnectionManager().shutdown();
httpGet.abort();
Log.i("log", "Before Return");
return "done";
}
#Override
protected void onPostExecute(String result) {
Log.i("log", "Async finished");
}
But post is called after 60 seconds.May i know why it is happening
I got two to three execption when calling webservice from android apps. When i call the webservice from apps on 2.3.3(Emulator) version then i got exception like UnhostException , connectiontimeoutexception on 4.2.1(real device) version and working fine on 3.1 version, i don't know why this happen. I was trying to solve this exception from yesterday but solved yet, if any changes needed in the code then please suggest me.
In LoginActivity I call the method for making the http request
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", userpsw));
JsonParserWebs jsonDataFromSrvr = new JsonParserWebs();
String loginData = jsonDataFromSrvr.makeHttpReqToSrvr(loginUrl,"POST", params);
Following is the JsonParserWebs for calling webservice
public String makeHttpReqToSrvr(String url,String requestType,List<NameValuePair> params) {
Log.i(JsonParserWebs.class.getName(),"URL..."+url);
HttpEntity httpEntity=null;
//making http request
try {
if (requestType == "GET") {
//connection time out
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString =URLEncodedUtils.format(params, "utf-8");
HttpGet httpGet = new HttpGet(url+"?"+paramString);
HttpResponse httpResp = httpClient.execute(httpGet);
httpEntity = httpResp.getEntity();
}
if (requestType == "POST") {
//connection time out
// From stackoverflow, I addes following three line but still got ConnectTimeoutException
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResp = httpClient.execute(httpPost);
httpEntity = httpResp.getEntity();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
json = EntityUtils.toString(httpEntity);
Log.v("JSON", "data"+json);
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
return json;
}
Thanks in Advance
You need to use AsyncTask , otherwise it will crash!
1. use AsyncTask when ever you use time consuming process other wise you will get network exception
2. take internet permission in .mainfeast
I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}
I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.
I am trying to connect to internet where I have to fetch data, if the time exceeds more than 5 secs to connect I have to finish the process & continue to work offline.
Everything is working fine, sometimes it takes around 10secs to return when internet is not available, Now I have to return the xml == null; when the time exceeds more than time limit,
I don't want to do this in Async Task
public String getUrlData(String url) {
String xml = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
// check if the timer has exceeded by "if else"
// move to "return xml;" Manually when exceeds 5sec, but how?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xml;
}
Edited Code after this answer
public String getUrlData(String url) {
String xml = null;
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
System.out.println("Started");
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Ended");
return xml;
}
LogCat Here >> 20 Secs
All you need to do is to define a timeout limit for your connections. For example:
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpClient = new DefaultHttpClient(httpParams);
and afterwards, use httpClient in the same way you are using it.
Edit
public String getUrlData(String url) {
String xml = null;
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
// check if the timer has exceeded by "if else"
// move to "return xml;" Manually when exceeds 5sec, but how?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xml;
}
How about this:
Thread thread = new Thread() {
#Override
public void run() {
// do the downloading thing..
}
};
thread.start();
thread.join(5000);
This is just an idea, but you could set up a delayed runnable and check after 5 seconds if the file has any size.
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Don't handle redirects -- return them to the caller. Our code
// often wants to re-POST after a redirect, which we must do ourselves.
HttpClientParams.setRedirecting(params, false);
// Use a session cache for SSL sockets
SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
// Set the specified user agent and register standard protocols.
HttpProtocolParams.setUserAgent(params, userAgent);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https",
SSLCertificateSocketFactory.getHttpSocketFactory(
SOCKET_OPERATION_TIMEOUT, sessionCache), 443));
ClientConnectionManager manager =
new ThreadSafeClientConnManager(params, schemeRegistry);
// We use a factory method to modify superclass initialization
// parameters without the funny call-a-static-method dance.
return new AndroidHttpClient(manager, params);
Change SOCKET_OPERATION_TIMEOUT value according to your need.
This code may help you
this code from last answer is Ok
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpClient = new DefaultHttpClient(httpParams);
Only when you are trying to execute your request you have to care about 3 more exceptions
SocketTimeoutException, UnknownHostException, ConnectTimeoutException
so catch this 3 exceptions also.
I need to do a HTTP post to a web service..
If I place this into a web browser like this
http://server/ilwebservice.asmx/PlaceGPSCords?userid=99&longitude=-25.258&latitude=25.2548
then is stores the values to our DB on the server..
In Eclipse, using Java programming for android.. The url will look like
http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+"
with uid, lng1 and lat1 being assigned as strings..
How would I run this?
Thanks
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}
For http post use name value pair. See below code -
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("longitude", long1));
nameValuePairs.add(new BasicNameValuePair("latitude", lat1));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
Infact I had done already what you are going to do. So try this stff. You can create a method like this what I have and pass your URL with lat, long. This is return you the response of the HTTP connection.
public static int sendData(String url) throws IOException
{
try{
urlobj = new URL(url);
conn = urlobj.openConnection();
httpconn= (HttpURLConnection)conn;
httpconn.setConnectTimeout(5000);
httpconn.setDoInput(true);
}
catch(Exception e){
e.printStackTrace();}
try{
responseCode = httpconn.getResponseCode();}
catch(Exception e){
responseCode = -1;
e.printStackTrace();
}
return responseCode;
}
I'm not sure I understood your question, but if I did I think you can use java.net.UrlConnection :
URL url = new URL("http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1);
URLConnection conn = url.openConnection();
conn.connect();