Summary of network operation usage in Android (HTTP)

Source: Internet
Author: User
Tags response code

Android is the operating system as a smartphone, most of the applications we develop need to be connected to the network, send data over the network, get data, so as an application developer must be familiar with how network access and connectivity. Usually in the Android network connection is generally using Scoket or http,http is the most cases, here, I come to summarize, how to do HTTP network access operation.

Android is developed in the Java language, and the Android package contains Java urlconnection and Apache HttpClient, so we can use both tools for network connectivity and operation. At the same time, in order to control whether the program is allowed to connect to the network, when we develop the application, we need to configure the permission to request a network connection in the manifest file, code as follows.

<uses-permission android:name="android.permission.INTERNET"/>
Connect to a network using URLConnection

URLConnection for the network access provided in the java.net package, support HTTP,HTTPS,FTP, etc., when making an HTTP connection, use HttpURLConnection, the sample code is as follows:

url url = new URL (" http://www.android.com/"); HttpURLConnection URLConnection = (httpurlconnection) url.openconnection (); try {inputstream in = new BufferedInputStre    AM (Urlconnection.getinputstream ());   Readstream (in); This method is written by ourselves, from the stream to save the data to the local, to achieve from the network to obtain data. finally {urlconnection.disconnect ();}  

When you submit data to the server, you need to use the post transport

httpurlconnection urlconnection = (httpurlconnection) url.openconnection (); try {    Urlconnection.setdooutput (TRUE);    Settings can be uploaded data urlconnection.setchunkedstreamingmode (0);    OutputStream out = new Bufferedoutputstream (Urlconnection.getoutputstream ());   Writestream (out);    This method is written by ourselves, to the output stream to write data, to achieve data upload.    InputStream in = new Bufferedinputstream (Urlconnection.getinputstream ()); Readstream (in); finally {urlconnection.disconnect ();}  

For more usage methods and functions, see: http://developer.android.com/reference/java/net/HttpURLConnection.html

At the same time httpsurlconnection the use of the method please view: http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html

Using HttpClient

In this case, we can also use the Androidhttpclient page can use the Apache default Deafulthttpclient, the two are only common client different, the others are the same

Create Androidhttpclient

AndroidHttpClient httpClient = AndroidHttpClient.newInstance("user-agent");

Create Defaulthttpclient

HttpClient client = new DefaultHttpClient();

GET request

httpget getrequest = new HttpGet (" http://blog.isming.me "); try {httpresponse response = HTTPCLIENT.E Xecute (GetMethod); Initiate a GET request log.i (TAG, "Rescode =" + Response.getstatusline (). Getstatuscode ()); Get the response code LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8"));//Get server response content} catch (Clientpro  Tocolexception e) {//TODO auto-generated catch block E.printstacktrace ();  } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }

initiating a POST request:

First the data to be passed into the list params = new linkedlist<basicnamevaluepair> ();  Params.add (New Basicnamevaluepair ("param1", "POST Method"));  Params.add (New Basicnamevaluepair ("Param2", "second parameter"));      try {httppost Postmethod = new HttpPost (BASEURL); Postmethod.setentity (New urlencodedformentity (params, "utf-8")); Fill in the parameters into post entity httpresponse response = Httpclient.execute (Postmethod); Execute the Post method log.i (TAG, "Rescode =" + Response.getstatusline (). Getstatuscode ()); Get the response code LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8"));  Get response content} catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.printstacktrace ();  } catch (Clientprotocolexception e) {//TODO auto-generated catch block E.printstacktrace ();  } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }
Description

As seen from above, using httpclient is more convenient and clear. However, the official Android documentation for us is recommended android2.2 and the following versions recommend using the httpclient,android2.3 and the HttpURLConnection.

The reason is that when httpurlconnection a lightweight HTTP client, the API is simple and easy to extend, but in 2.2 and previous versions, the API has some bugs, in the 2.3 version, it was modified.

While HttpClient stable, fewer bugs, but it provides a lot of APIs, upgrades and extensions are inconvenient, the Android team in the promotion and optimization of their enthusiasm is not high.

Therefore, before the Android2.2 version, the best choice when using HttpClient.
Android2.3 version and later, the best choice when using HttpURLConnection.

Framework

A network connection is a time-consuming operation, and usually we do not put it in the UI thread operation, it writes an asynchronous thread and puts it in the background thread execution (see here for asynchronous threading operations).

While there are some threads on the network operating framework, can reduce our workload, while we write a good, may be a lot of exception handling and so on, without its more comprehensive.

With a light weight of android-async-http
Google's official volley
Square offers the retrofit

This can be based on the needs of their own project to choose a different framework, there is no time for me to write the use of Volley ( PS:网上已经有使用方法了,自己百度去 ), the other two of my connection has been used.

OK, finish!
Write a lot of things, but the introduction of not enough detail. If it's not clear, please talk to me.

Original address: Http://blog.isming.me/blog/2014/05/11/use-network-in-android/, welcome reprint, reproduced please indicate the source!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.