json and http client slow - android

I have a json parser which is parsing from a url, the app works on WiFi without problems and fast enough but on mobile network it's very slow and most of time not working.
The speed of the mobile network is good enough that whatsapp is working fast, so I don't know if the problem is related to Json parser or http client.
// Async Task to access the web
public String makeHttpRequest(String url, String method,
List<NameValuePair> params) {
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params1);
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return JSON String
return jsonResult;
}

use any third party tools,which have inbuilt features to make your request fast.
AsyncHttpClient :
HTTP requests happen outside the UI thread
Automatic gzip response decoding support for super-fast requests
Retrofit
finally Volley
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster
You can see this information from developer.android.com-training-volley

Related

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

httpclient.execute(httpPost) error

In my android application I try to send a json object to a distant server, when I run it I get an error in httpclient.execute(httpPost)
This is a part of my code.
public static String GET(String url , JSONObject js){
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "Basic **********");
httpPost.setEntity(new StringEntity(js.toString()));
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(httpPost);
} catch (Exception e) {
Log.i("Console", "Error");
}
Any help please.
I guess your Problem is, that you try to run your Network Request from your Main Thread.
I would discourage you to use the Apache HTTP Client at all.
It became deprecated for Marshmallow, see here
Maybe try OkHttp. It offers you the possibility to run a request asynchronously.

I have got Socket Timeout Exception but My data submitted on server too

I have got an prob with http post request i have set time out and on socket time out exception my data submitted on server successfully how i can restrict data to submitted on server my code is following
try{HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
AppSettings.SERVICE_URL.POST_NEW_REGISTRATION);
HttpConnectionParams.setConnectionTimeout(
httpClient.getParams(), 5000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
JSONObject jsonObject = new JSONObject();
jsonObject.put("agent_id", SharedPrefrence.getUserID());
httpPost.setEntity(new StringEntity(jsonObject.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
// Execute POST
//int getConnectionTimeout (HttpParams params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) {
response = EntityUtils.toString(responseEntity);
} else {
response = "{'success':'FALSE'}";
}
} catch (ClientProtocolException e) {
response = "{'success':'FALSE'}";
progressDialog.cancel();
} catch (IOException e) {
response = "{'success':'FALSE','message':'Connection Time Out'}";
Log.d("Ex", e.toString());
Log.e("Ex", e.toString());
progressDialog.cancel();
} catch (JSONException e) {
response = "{'success':'FALSE','message':'JSON Parse Error'}";
progressDialog.cancel();
e.printStackTrace();
} catch (Exception e) {
response = "{'success':'FALSE'}";
progressDialog.cancel();
e.printStackTrace();
}
I think you are saying that you are getting a socket timeout exception even though the data is successfully received by the server?
If so, I think you may want to look at the value you are setting for the socket timeout - this appears to be 500ms in your code, which is quite short. It is quite possible that everything on the server side is working fine, but that the response is simply not getting to the client within 500ms.
A typical default is in the 6-10 seconds range, but it is really solution dependent so you may want to experiment. This blog post suggests some defaults for different scenarios and may be a useful reference:
http://dev.bizo.com/2013/04/sensible-defaults-for-apache-httpclient.html
probably your API call takes more than 500 ms, increase it and try again.

Web Service using HTTP Protocol in Android

can anyone give me an idea of using web service using HTTP protocol.
Here is an example for "Executing a HTTP POST Request with HttpClient":
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "123"));
nameValuePairs.add(new BasicNameValuePair("username", "Paresh"));
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
}
}
We can use web services in our application to send and receive data from a remote server. Consider the case of an login section from a application where you need to pass username and password to the server for checking the whether the user is a valid user or not. In this case the username and password are attached with a url and send it to the remote server for validation and in response you get a value stating whether the user is a valid user or not. Usually the response will be either in XML format or JSON format from there we need to parse that response to get the necessary values. Check out the following example code in this I have created a class named "parsing" and it using the http protocol to receive a data.
public class parsing extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://services.digg.com/topics?appkey=http://example.com&type=json";
HttpPost post = new HttpPost(postURL);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
String response=EntityUtils.toString(resEntity);
response=response.trim();
Log.i("RESPONSE=",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See the response on the Logcat and do not for get to include <uses-permission android:name="android.permission.INTERNET" />
because we are fetching the data from the remote server which needs internet permission.

403 FORBIDDEN message when I use HttpPost to send data to Django

I am trying to send data from android to Django app. I want to store the data in a table in sqlite database called "mytable". Here is the android code:
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8000/androidweb/edit/");
JSONObject j = new JSONObject();
try {
j.put("name", "david");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("year", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// myTextView.setText(j.toString());
HttpResponse response = httpclient.execute(httppost);
myTextView.setText(response.getStatusLine().toString());
// myTextView.setText(response.toString());
}catch(Exception e) {
myTextView.setText("Error in http connection "+e.toString());
}
The issue is resolved now. I only needed to have a return value
Sounds like Django's Cross-Site Request Forgery framework, which by default prevents third-party POST requests. Read Django's CSRF docs for details.

Categories

Resources