i am currently working on an android app which includes a HTML-code-download feauture. However, the execution via HttpClient is very slow and takes about 12 seconds for a page which loads in 1 or 2 seconds via phone browser. I already tried using HttpURLConnection, but it downloads the code in roughly the same time. What would you peoplerecommend me changing?
public class Downloader extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
String url = params[0];
String htmlcode = "FAIL";
try{
Log.i("METAMETER","DL: INITIALIZING");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 1000);
Log.i("METAMETER","DL: EXECUTING");
HttpResponse response = client.execute(request);
//Apparently the step above takes about 12 seconds for a page which only takes 1-2 seconds via browser
Log.i("METAMETER","DL: WRITING");
htmlcode = EntityUtils.toString(response.getEntity());
}catch (Exception e){htmlcode = "EXCEPTION";}
Log.i("METAMETER","DL: DONE");
return htmlcode;
}
}
Instead of
HttpClient client = new DefaultHttpClient();
Try using
HttpClient client = AndroidHttpClient.newInstance("MyApp/1.0");
Related
i am new in Android development and now i am developing small application of google map. i have integrated google map,but now i want to show google places on map therefore i want to call google api web service to get locations, but i don't know how to call web service in android.enter code here
enter code here
public void getLocation()
{
HttpClient httpClient = new HttpClient()
AsyncHttpClient client =new AsyncHttpClient();
}
You can call Url's with HttpConnection.
For Example:
public String getValuefromUrl(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
Log.v("PAGE",page);
return page;
}
catch(Exception ex)
{
ex.printStackTrace();
return "zero";
}
}
In my application I have been using DefaultHttpClient for uploading images to the server but it takes too much time to give response when server is down. I have put my code here. And AFIK DefaultHttpClient is going to be deprecated, so I want to use OkHttp instead of DefaultHttpClient. So please help me to change my code to use OkHttp for uploading images. I have searched a lot but don't know how to make the changes. please help me....
public String upLoadImg(byte[] image,String name,String phone,String imei,String randomId){
String mResponseData = null;
try{
mHttpClient = new DefaultHttpClient();
mHttpPost = new HttpPost(Constants.BASE_URL +"user/asset");
mHttpPost.setHeader("Accept", "application/json");
mHttpPost.setHeader("mobile-number", phone);
mHttpPost.setHeader("uid", imei);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(image !=null) {
ByteArrayBody bab = new ByteArrayBody(image, name);
reqEntity.addPart("file", bab);
}
mHttpPost.setEntity(reqEntity);
Log.e("TAG", "***** mHttpClient is going to execute ");
HttpParams httpParameters = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 2 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 2 * 1000);
mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity resEntity = null;
if(mHttpResponse!=null)
resEntity = mHttpResponse.getEntity();
if(resEntity!=null)
mResponseData = EntityUtils.toString(resEntity).trim();
}catch(HttpHostConnectException e){
Log.e("TAG","Exception cannot connect to server while sending images ",e);
return null;
}catch(Exception e){
Log.e("TAG","Exception occured while sending images ",e);
return null;
}
return mResponseData;
}
I had overcame this issue by replacing DefaultHttpClient with Okhttpclient.
As far as i know DefaultHttpClient is deprecated in latest android versions.So i had switched to OkHttpClient and then all issues fixed
I am requesting a HTTP request from Android Emulator but its getting failed .. Is there any issue with the emulator?
I have also enabled internet connection permission from Manifest
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://androidexample.com/media/webservice/httpget.php?user="+loginValue+"&name="+fnameValue+"&email="+emailValue+"&pass="+passValue;
//Log.i("httpget", URL);
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
I am using below link to test on emulator
http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88
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.
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...");
}