What exactly these lines do individually and collectively in JSON parsing - android

I am wondering after I searched in few books and on web that none of then detailed about it. I want to know that what exactly the purpose of below line individually while we parse JSON response file :
Lines ARE :
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
I know one thing that all together these four lines perform the connection with the server, but have no idea what individually the do.
I am sure I will get answer here from one of SOF besties.

Android's DefaultHttpClient Supports:
HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.
HttpPost :
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
HttpResponse :
Takes care of the response that is got after executing client.execute(post);
Finally the following code obtains the message entity of this response.
response.getEntity()
Please check the android documentation for detailed implementation.

Code above is resposible for Http post request to server and get JSON response, so that you can parse and get required data.

Above 4 lines don't do JSON parsing. They only make an HTTP connection and the way of doing it is only recommended below Gingerbread. For Gingerbread and above use HttpURLConnection. More details here.
After you have the content (make a check if the response code is as expected - 200 or 201) you can proceed to JSON parsing. Use either Jackson, GSON or Android's json framework (this is my preferred order).

As per may Opinion
DefaultHttpClient client=new DefaultHttpClient(); responsible for HttpsURLConnection efficient(Connection) when connecting to up-to-date servers, without breaking compatibility with older ones.
HttpPost post = new HttpPost(Url); responsible for get POST request and send response.
HttpResponse response = client.execute(post); responsible for executes HTTP request using the default context.
HttpEntity entity = response.getEntity(); responsible for carry a content entity associated with the request or response.
For more information go to:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

Related

How do i represent this cURL command in java on android?

The command is
curl http://localhost:port -H 'Authorization: Token token=blahblahblah'
I am currently using this approach:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String authString = "Token " + "3589c4cd8c18f077bf43b4c4b7415d"; // <~token
httpPost.setHeader("Authorization", authString);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
I just get a bad token back meaning that I did not successfully login from my android client. However the curl command i post works fine. So I believe I am not implementing the http Post correctly on my app. Thanks!
Your curl command has the header as:
Token token=blahblahblah
Your Java has the header as:
Token 3589c4cd8c18f077bf43b4c4b7415d
You are missing the token= part.
Also, HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. I encourage you to move to some other HTTP API. That could be:
the built-in classic Java HttpUrlConnection
Apache's independent packaging of HttpClient for Android
OkHttp (my recommendation)
AndroidAsync
Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).

What is the preferable method for sending request in mobile API in Rails

I have created an API controller to handle only json requests from an Android app. Naturally I'm using token authentication. What would be better:
To send a request using POST:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.170:3000/api/get_all");
httppost.setHeader("content-type", "application/json; charset= utf-8");
httppost.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("token", token);
StringEntity entity = new StringEntity(json.toString(), "utf-8");
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
or GET:
httpget = new HttpGet("http://10.0.0.170:3000/api/get_all?"+"token="+token);
httpget.setHeader("content-type", "application/json; charset= utf-8");
httpget.setHeader("Accept", "application/json");
response = httpclient.execute(httpget);
result = EntityUtils.toString(response.getEntity());
clearly there is less code in GET, but is there some other reasons to prefer one over the other?
Even if you are using this token for simple lookup, i.e. without changing the state on server, use POST. If you use GET, web server will log all query parameters making it more vulnerable for log injection attacks for example.
You should also consider using HTTPS for authentication token in production.
In your code consider also handling return status from web server (e.g. when it is not 200).
In general, for the choice POST vs GET you can also refer to W3C:
Use GET if:
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.

How can i improve performance of calling web services in android?

I developed an android application using web services. Here i am calling web services to get data from server and showed in my application views. Application is working fine but calling web services is gave me performance issues. It will take more time to get data.
I am using the below code to call api and used handler to parse the data. And my result is in XML format. I am using SAX parser to parse data. I don't know why the application is very slow to get data and parse. Please provide me good performance service hint for me.
Here is my api calling code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
StringEntity entity = null;
entity = new StringEntity(xmlRequest, HTTP.UTF_8);
httppost.setHeader("Content-Type", "text/xml");
httppost.setEntity(se);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
InputStream is = httpResponse.getEntity().getContent();
I am converting this input stream to string builder and parsing.
Thanks in advance.

http async response for large response

I'm familiar with android HTTPURLConnection and apache HTTPConnection classes and the way they work (they are all synchronous, but I can live with that).
I have a large response with many lines of data comming from the server. It's a JSON response and I can display the data partially before I parsed all the response. Some json parsers allow that (like xcers allows for xml). Do the callbacks and methods related to the two classes mentioned above allow it? When I get the response from HTTPURLConnection upon opening input stream and read, do I open the stream when ALL the data is already there? Or can I open and read it and more that should follow?
Also, is there any http method on android that works with NIO?
With HttpClient, when you open the response stream like this:
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
and start reading, you actually start the downloading and you get new bytes as soon as these are received. You don't wait for everything to get downloaded to start reading.
As far as I know the HttpClient that is bundled with Android is not based on NIO. I don't know of any alternative that does so.
In addition to all of the possible solutions in Ladlestein's comment, there's the simple answer of wrapping all that in an AsyncTask. Here is a sample project demonstrating doing an HTTP request using HttpClient in an AsyncTask.

Android persistent HttpClient connection

Would it be possible to setup an HttpClient such that on a website that updates periodically, perhaps due to AJAX, the resulting changes would be captured by the HttpClient. Similar to keeping a connection to a website alive, and if there were an update, the HttpClient would send the updated response to a listener of some type. I feel as if there is an obvious answer to my question, but I just haven't found it because I may have some of my terminology wrong...
This is just an example snippet of how I usually set up a connection:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
Welcome to Stack Overflow! I do not think keeping a constant connection open to your site would be the best solution. Why don't you just poll every once in awhile?

Categories

Resources