http async response for large response - android

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.

Related

Android Compress data for posting to web server

I am still a beginner in Android. I am currently sending large amount of data(json) from the android app to web server using HTTPClient. I found that HttpURLConnection supports decompression for request but is there any support or any way that I can upload a compress/gzipped json to the web server?
Is the only way to achieve this is to manually gzip the json string and put the gzipped string into in to the post?
You can add GZIP compression in your HTTP header.
HttpUriRequest request = new HttpGet(url);
request.addHeader("Content-Encoding", "gzip");
// ...
httpClient.execute(request);
You can check this link for more information

What exactly these lines do individually and collectively in JSON parsing

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

Right way to manage HTTP connection in Android

I have written two programs which handle the HTTP request. I wanted to know if one is better than other -
Program 1 (Using HttpURLConnection)
URL url = new URL("https://www.google.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
Program 2 (Using HttpPost)
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://test.com");
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
Also in program 2, I use a singleton to get the connection object. But in program 1 there is no global connection object and I need to recreate the HttpURLConnection object everytime I make a request. Please let me know if I am on the right track.
Thank You
I would like to suggest you to use Android Asynchronous Http Client library.
Then you can avoid these basic stuffs. The one things I like most is HTTP requests happen outside the UI thread.
Also in program 2, I use a singleton to get the connection object. But in program 1 there is no global connection object and I need to recreate the HttpURLConnection object everytime I make a request.
Method 2 looks like simpler, but it's so old :
Apache HTTP Client - HTTPPost
DefaultHttpClient and its sibling AndroidHttpClient are extensible
HTTP clients suitable for web browsers. They have large and flexible
APIs. Their implementation is stable and they have few bugs. But the
large size of this API makes it difficult for us to improve it without
breaking compatibility. The Android team is not actively working on
Apache HTTP Client.
HttpURLConnection
HttpURLConnection is a general-purpose, lightweight HTTP client
suitable for most applications. This class has humble beginnings, but
its focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs.
We should choose method 1 when :
For Gingerbread and better, HttpURLConnection is the best choice. Its
simple API and small size makes it great fit for Android. Transparent
compression and response caching reduce network use, improve speed and
save battery. New applications should use HttpURLConnection; it is
where we will be spending our energy going forward.
And method 2 when :
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
Thanks,

Android app getting data from a third-party JSP & Servlet

I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.

dfference between using URLCOnnection Object and Httppost in android client

I am using URLConnection Object to send data from my android client to server.
URL url = new URL("http://10.0.2.2:8080/hello");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());
String s="check"+","+susername;
out.writeObject(s);
out.flush();
out.close();
But I have seen many android programs sending data using httppost in the following way.
HttpClient client=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(LOGIN_ADDRESS);
List pairs=new ArrayList();
String strUsername=username.getText().toString();
String strPassword=password.getText().toString();
pairs.add(new BasicNameValuePair("username", strUsername));
pairs.add(new BasicNameValuePair("password", strPassword));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response= client.execute(httpPost);
please explain the differnce between the two. How would you receive the data in the later case in a servlet. please give a brief explanation on this HttpPost. In the internet all I find is code. pls give a step by step explanation on HttpPost and its methods and how should the data be received in the servlet. Links will do fine.
This blog post does a pretty good job of explaining the difference between the two of them (well actually HttpURLConnection, but that's just a subclass of URLConnection). Some highlights from the article are:
HttpURLConnection easily allows gzip encoding
HttpURLConnection can allow for easy caching of results
HttpURLConnection is newer and being actively developed on so it's only going to get faster and better
HttpURLConnection has some annoying bugs on foryo and pre-froyo platforms
HttpClient is tried and true. It's been around for a long time and it works
HttpClient is pretty much not being developed on because it's so old and the API is completely locked down. There isn't much more the android developers can do in terms of making it better.
While the end of the article recommends use of HttpURLConnection on all platforms above froyo, I personally like using HttpClient no matter what. It's just easier to use for me and makes more sense. But if you're already using HttpURLConnection, you should totally keep using it. It's going to be receiving lot's of love from the android developers from here-on-out.

Categories

Resources