Android is the operating system for smartphones, and most of the applications we develop need to connect to the network, send data over the network, and get data, so as an application developer, you must be familiar with how to access and connect to the Internet.
Usually the network connection in Android is usually using Scoket or http,http is the most common situation. Here, let me summarize. How to perform an HTTP network access operation.
Android is developed in the Java language, and the Android package includes 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 connects to the network, when we develop the application, we need to configure the permission to request the network connection in the manifest file, such as the following code.
<uses-permission android:name="android.permission.INTERNET"/>
Connect to a network using URLConnection
URLConnection for network access in the java.net package. Support Http,https,ftp and so on. When you make an HTTP connection. You can use HttpURLConnection. The demo 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); The method is written by ourselves, and the data is saved locally from the stream. Achieve data acquisition from the network.
finally {urlconnection.disconnect ();}
When submitting data to the server, you need to use the post transport
httpurlconnection urlconnection = (httpurlconnection) url.openconnection (); try { Urlconnection.setdooutput (TRUE); Set the ability to upload data urlconnection.setchunkedstreamingmode (0); OutputStream out = new Bufferedoutputstream (Urlconnection.getoutputstream ()); Writestream (out); This method is written by us ourselves. Writes data to the output stream for data uploads. InputStream in = new Bufferedinputstream (Urlconnection.getinputstream ()); Readstream (in); finally {urlconnection.disconnect ();}
Many other usages and functions see: http://developer.android.com/reference/java/net/HttpURLConnection.html
At the same time httpsurlconnection usage please view: http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html
Using HttpClient
In this case, we can also use the Androidhttpclient page to use the Apache default deafulthttpclient, the only common client is 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 (Client Protocolexception 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 number of references in post entity HttpResponse response = Httpclient.execute (Postmethod); Run 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.
Just Android official to US document description is recommended android2.2 and the following version number recommended using httpclient,android2.3 and above version number recommended httpurlconnection.
The reason is that when httpurlconnection a lightweight httpclient, the API is simpler and easier to extend, but there are some bugs in this API in the 2.2 and the previous version numbers. In the 2.3 version number, the change was made.
While HttpClient is stable and has fewer bugs, it offers a lot of APIs, is not easy to upgrade and expand, and the Android team has a low incentive to improve and optimize it.
Therefore, the Android2.2 version number was once. The best choice when using HttpClient.
Android2.3 version number and later, the best choice when using HttpURLConnection.
Framework
Network connectivity is a time-consuming operation. Usually we don't put it in the UI threading operation. The asynchronous thread is written and placed in a background thread (asynchronous thread operations see here).
And there are some threads on the network operating framework, can reduce our workload, at the same time we write well, may be very much exception handling and so on. Without its being 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 projects to choose a different framework, there is time for me to write the use of Volley ( PS:网上已经有用法了。自己百度去
), the other two of my connection has been used.
OK, finished!
Write a lot of things. But the introduction is not specific enough.
Assumptions are unclear. Welcome to communicate with me
Original address: Http://blog.isming.me/blog/2014/05/11/use-network-in-android/, welcome reprint, reproduced please indicate the source!
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Android Network Operation Usage Rollup (HTTP)