dfference between using URLCOnnection Object and Httppost in android client - android

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.

Related

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.

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.

HTTP POST and RESPONSE specific case study

Site: http://na.leagueoflegends.com/ladders/solo-5x5
Search for a a player (example: Jaiybe)
You get redirected (in this case to: http://na.leagueoflegends.com/ladders/solo-5x5?highlight=28&page=1)
Read the content
And I want to do that in java/android.
I analyze the sites POST request when searching, result:
op:Search
player:Jaiybe
ladder_id:3
form_build_id:form-fff5e6e2569f1e15e5a5caf2a61c15e2
form_id:ladders_filter_form
Build a simple HTTP POST mixture and lets read the content...
The CODE:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");
// Add your POST METHOD attributes
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("op", "Search"));
nameValuePairs.add(new BasicNameValuePair("player", Jaiybe));
nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
nameValuePairs.add(new BasicNameValuePair("form_build_id","form-daca6fff89cedc352ccc3f533afa3804"));
nameValuePairs.add(new BasicNameValuePair("form_id","ladders_filter_form"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
return responseBody;
And when I run it - I get so some kind of a offline page...
The number form_build_id - is constantly changing, but this was no problem, to use still the same one, and also If I would like to "test" if this could be the problem, I have no Idea how would I...
OR: Is there any other - FAST - way how to get same results?
What is strange is that the "error" site source code that I get on android is different as if I run the same on my PC (Win7, Eclipse, Java) or in my browser. As if there would be two versions of offline sites - for mobile and for PC - but my question: HOW WOULD the server know that the code runs on a Android device? Is there a way how to set this up in HttpClient?
form_build_id:form-fff5e6e2569f1e15e5a5caf2a61c15e2
This is an auto generated token that is valid for a certain time period. This is probably the source of your problem and the reason the token exists in the first place (to prevent post spams).
As this token does not seem session based, you could actually use an HTTP Get on the page that generates the form and parse out the generated token each time for your HTTP Post.
About OS detection, browsers usually provide information about the OS using the HTTP User-Agent header.

Server in Java(Http/sockets)

I want to build an Http Server which will serve the requests of a chat application in android. Because i am really confused... in my code I have to use sockets? How can i make the client to communicate with the server? Which is the code i have to add in the server in order to accept the requests from the client and respond to them? The code I use in the client is the following:
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:80");
List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
nvps.add(new BasicNameValuePair("username", username1));
nvps.add(new BasicNameValuePair("password", password1));
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);
//Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
Log.v(TAG,"something");
Log.v(TAG, response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Please I really need an answer. Thank you!!!
Sockets (Socket for client, ServerSocket for server) is the most basic layer of communication. You chose TCP or UDP and over it, you need to encode all of your protocol.
There are also some libraries that encode higher level protocols (HTTP, FTP, and even higher as SOAP). If you use these libraries, you usually do not need to manage socket as it is done by the library itself (in the server you only specify port and optionally IP to bind to; in the client you specify host and port to connect to).
You can use different combinations (v.g. implementing your server with SOAP and then creating and sending a SOAP message from the client using Socket) but the simplest way is to use the same library both for the server and client.
About which one is better: it depends of what you want it to. Higher level libraries are more flexible but may take a time to master and may have more overhead, lower level needs that you manage everything. If there is no more compelling reason, I usually just use the HTTP protocol (both from the JVM or from the Apache Foundation projects).

Categories

Resources