Android Check how fast post request took - android

I am trying to check how fast a Post request took to execute. I am doing the request inside an AsyncTask.
This is how I am currently checking for execution time
long start = System.nanoTime();
new POSTTask().execute();
long end = System.nanoTime() - start;
I am not sure if the time given by this is the actual time it takes for the Post request. Inside the AsyncTask the only thing I am doing is the following
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("test", "tets1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = httpClient.execute(request);
result = EntityUtils.toString(response.getEntity());
Log.i("Result", result);
} catch (IOException e) {
e.printStackTrace();
}
Am I going about this the right way or the wrong way?

No, its not the actual time. You are trying to get execution time on main thread but your post query is running in a different thread in background.
Use it like this
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("test", "tets1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
long start = System.nanoTime();
HttpResponse response = httpClient.execute(request);
long end = System.nanoTime() - start;
// Print value of end here
result = EntityUtils.toString(response.getEntity());
Log.i("Result", result);
} catch (IOException e) {
e.printStackTrace();
}

Nope, this is wrong. The execute method on an AsyncTask returns immediately, before the request has been performed.
If you move the timing code into the AsyncTask, specifically by putting it around this line
HttpResponse response = httpClient.execute(request);
you will get the actual time.

that is wrong as those lines do not execute in order.
new POSTTask().execute();
starts a new thread meaning your 2 time stamps are going to be really close together like milliseconds apart and thats not accurate
what you should be doing all your timing in your doInBackground

Related

How to handle the situation when server is down on my android side

Here is my doInBackground() method in which I call my makeHttpRequest() method which is in other class.
protected String doInBackground(Integer... args) {
// Building Parameters
String parameter1 = "tenant";
String parameter2 = "price";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("person",parameter1));
params.add(new BasicNameValuePair("price",parameter2));
JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);
Log.d("Details", json.toString());
int success = json.getInt("connected");
if (success == 1) {
//blah blah
}
}
makeHttpRequest() method:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
................
....................... // Here the result is extracted and made it to json object
.............................
// return JSON
return jObj; // returning the json object to the method that calls.
}
So, by the above code, the actual call to the server is made by this line -> HttpResponse httpResponse = httpClient.execute(httpPost);
When my server is up everything works fine, but when it is down the progress bar continuously loads. I want to handle this situation. Have done lot of search, but could find only this post. This looks good for my situation because even my thought is to wait for the 10 seconds to get the response and if it exceeds that time out, I need to handle it to show the message in the catch block. But I am unable to implement it according to my code. Can some one please help me on this? I would be very thankful.
Your exceptions are not getting hit because the HttpClient is not throwing an exception. Perhaps you are getting an error in your HttpResponse code, such as a 500. In your try block, add this line:
response.getStatusLine().getStatusCode()
Then read the status code. If your web server is up you should get a 200 OK, but if it's down, you'll probably get a 500 or something else. You can then handle the code here where your spinning progress bar needs to be hidden, and an error message can be displayed.
Add Following Code before executing the url.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
write the above code in try block and Catch ConnectTimeOutException and SocketConnectionTimeOutException. Where you can show some custom dialog.
You can also judge it by checking the status line of HttpClient Response.

it didn't work to connect the android app to servlet page to passing data

i want to connect my android app to my servlet site ,, that i need to pass some data from the app to the url
Can anyone help me?
I have written this code to pass two parameters but it generates an exception:
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
it seems that you are blocking the UI thread , and ANR Exception is raised since if your UI Thread is blocked for 5 second this exception will occur , to come over this issue you can use Thread or AsyncTask to do the job ,so your UI thread don't get blocked
example :
public myAsnyc extends AsyncTask<Void, Void,Void>{
protected void doInBackground(){
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
}
protected void onPostExecute(){
log.d("myApp", "success");
}
}
and if you want to execute it
make this call
new myAsnyc().execute();
if you want to update the UI elements use the onPostExecute() method and modify the generic type of the async task
UPDATE
execute the following code
use this code
try {
InetAddress i = InetAddress.getByName("http://androidsaveitem.appspot.com/view");
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
before you call the async task
if the exception occur fine , re run the app second time it will run normally

How to send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.

HTTP Post OK, how to display the response?

I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());

Cancel AsyncTask when HTTPPost fails?

I'm trying to cancel my AsyncTask when connecting to the server fails. I tried cancel(), but the onPostExecute() method still gets called, instead of onCancelled().
This is what I have inside doInBackground():
protected String doInBackground(String... params) {
Log.i("ping", "doInBackground() started");
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse response;
HttpEntity entity;
try {
HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", getEmail()));
nvps.add(new BasicNameValuePair("password", getPassword()));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream iStream = entity.getContent();
read(iStream);
iStream.close();
if(entity != null)
entity.consumeContent();
Log.i("ping", "doInBackground() vervolgd");
} catch (Exception e) {
e.printStackTrace();
Log.e("tvsping", "Exception: " + e.getMessage());
cancel(true);
}
return null;
}
I'm trying to see what happens when the server can't be reached (I'm shutting it down, so there's no way my phone is getting any response) and I get IOException: the connection was reset.
Any ideas how I should check if the connection isn't made?
update
I solved this like Tanmay suggested, with a boolean. But I have another problem:
Every time doInBackground() is called it takes about three minutes to stop, when it can't find the servers. Everything is fine when it can reach the server, but I can't have this taking 3 minutes before the user is notified of anything (I could do a background process, but still a 3 minute wating bar is no good neither)
Any ideas what is wrong with my code? This can't be normal, right?
From doInBackground() method you are returning a String .You can return null if your HTTPPost fails.And then in onPostExecute() method just check what are you getting, if the String is null dont do anything which you really want and on successful running do your UI work
Hope this will help you.
HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");
response = client.execute(target, post);
This solved the slow server response for me.

Categories

Resources