Right way to manage HTTP connection in Android - 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,

Related

Android connect to Mysql database tutorial

Does anybody know a complete and working tutorial about how to retrieve data from MYSQL and display it in Android? I'm asking this because all the tutorials I found are older than API 22 and from API 22 the HttpClient is deprecated. And I'm a new Android Developer so I can't write any code on my own. :)
HttpClient
Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
This interface was deprecated in API level 22.
Please use openConnection() instead.
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.
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.
Please visit this webpage for further details.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.
Uses of this class follow a pattern:
Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
For example, to retrieve the webpage at http://www.android.com/:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Please visit this webpage for further details.
http://developer.android.com/reference/java/net/HttpURLConnection.html
urlconnection tutorials, can visit this websites
+http://www.vogella.com/tutorials/AndroidNetworking/article.html
+http://javatechig.com/android/android-networking-tutorial

CSE (Custom Search Engine) steps

EDIT
...I'm still wondering why I can't find a solution to this issue.
I verify the API Key and the Custom Search Engine ID.
May be I left some library?
I have (related to the question):
-GWT SDK
-validation-api
I'm still reading posts and documentation....but nothing works....
ORIGINAL
I'm trying to develop an Android app. using CSE (Custom Search Engine). I've read a lot about this issue (here and in everywhere), but right now I'n not sure about anything: it's a mess for me.
I would like to know if I'm in the right way.
I get the API access key and the CSE ID
I want to use my own CSE, so I have to open a connection using "https://www.googleapis.com/customsearch/v1?key=_MY_API_KEY_&cx=_MY_SEARCH_ENGINE_ID&q=_MY_QUERY_
Here is the piece of code:
URL url = new URL("https://www.googleapis.com/customsearch/v1?key=_MY_KEY_&cx=_MY_ID_&q=tomcat");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
I get an SSL exception at
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
javax.net.ssl.SSLException: Connection closed by peer.
I don't know how I could fix this error, because all the examples I found related to CSE have (more or less) the same code to connect to the custom url search.
This is my first time here, so I not sure if I've expressed myself in the proper way.
Thanks a lot in advance.
Isaac.
I think you are trying to access a secure url (https) while using HttpURLConnection (instead HttpsURLConnection, mind the 's'), therefore the ssl error. Change to secure call and see if it worked.
To check if the engine is working as intended, just paste the url you mentioned ("https://www.googleapis.com/customsearch/v1?key=_MY_API_KEY_&cx=_MY_SEARCH_ENGINE_ID&q=_MY_QUERY_") in the browser - if it works, the engine is alright and the problem is in your code.

Measuring my app's network usage

Naturally I want to keep the network usage of my android app as low as possible, the question is how to measure it.
I managed to capture traffic with tcpdump and open it in wireshark, is that the way to go?
I have practically no idea on what all that stuff in wireshark means, obviously I have to read up on it, I just wanted to ask if there's a tutorial or tool ot whatever specifically for the aforementioned purpose?
Here you have very simple tutorial about measuring network usage.
You can also download this application and try to decompile it and watch the code.
try to use TrafficStats to statistics the system traffic .
Statistics the app traffic . if you use HttpClient ,try
HttpGet httpRequest = new HttpGet("http://xx.com/*");
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
int flowBytes = entity.getContentLength() ; //Traffic statistics
if you use URLConnection , try
URLConnection conn = imageUri.toURL().openConnection();
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
int flowBytes = conn.getContentLength() //Traffic statistics

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.

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.

Categories

Resources