Android Development Request Network Way detailed

Source: Internet
Author: User
Tags response code

Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/42643401

You know Google support and release of the Android mobile operating system, mainly to enable it to quickly occupy the market share of the mobile Internet, the so-called mobile Internet is also the Internet, any software involving the Internet, any program is the development of networked modules, It is true that Android networking is also a vital part of our development, so how does Android do networking? This blog is a simple introduction to Android's common networking options, including the httpclient supported by the JDK supported by Httpurlconnection,apache, and the introduction of some open source networking frameworks such as asynchttpclient. This blog only talk about the implementation process and methods, do not explain the principle, otherwise the principle of text is difficult to speak clear, in fact, we know how to use, you can solve some basic development needs.

The vast majority of Android applications are based on the HTTP protocol, and there are very few socket-based, we mainly explain the HTTP protocol-based networking approach. The walkthrough is built in a simulated login widget, and the login request data is only username and password two simple fields.


HttpURLConnection HttpURLConnection is a networking API provided in the JDK, we know that the Android SDK is Java based, so of course we prioritize httpurlconnection the most primitive and basic API, In fact, most of the open-source networking framework is basically a JDK-based httpurlconnection package, mastering httpurlconnection requires the following steps:

1 Convert the access path to a URL.

URL url = new URL (path);

2, get the connection through the URL.

HttpURLConnection conn = (httpurlconnection) url.openconnection ();

3, set the request mode.

Conn.setrequestmethod ("GET");

4, set the connection time-out.

Conn.setconnecttimeout (5000);

5, set the request header information.

Conn.setrequestproperty ("User-agent", "mozilla/5.0" (compatible; MSIE 9.0; Windows NT 6.1; trident/5.0) ");

6, get the response code

int code = Conn.getresponsecode ();

7, for different response codes, do a different operation

7.1, request code 200, indicating that the request was successful, get the input stream of the returned content

InputStream is = Conn.getinputstream ();

7.2. Convert input stream to string information

public class Streamtools {/** * converts the input stream into a string *  * @param is * The            input streams obtained from the network * @return */public static string Streamtostri  Ng (InputStream is) {try {bytearrayoutputstream BAOs = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len = 0;while (len = is.read (buffer))! =-1) {baos.write (buffer, 0, Len);} Baos.close (); Is.close (); byte[] ByteArray = Baos.tobytearray (); return new String (ByteArray);} catch (Exception e) {log.e ("tag", e.tostring ()); return null;}}}

7.3, if the return value 400, is the return network exception, the processing that responds.


HttpURLConnection sending a GET request

/** * Send GET request via HttpURLConnection *  * @param username * @param password * @return */public static String loginbyget (Str ing username, string password) {string path = "Http://192.168.0.107:8080/WebTest/LoginServerlet?username=" + Username + " &password= "+ password;try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"), int code = Conn.getresponsecode (), if (code = =) {InputStream is = Conn.getinputstream (); Byte stream converted to string return streamtools.streamtostring (is);} else {return "network access Failed";}} catch (Exception e) {e.printstacktrace (); return "network access Failed";}}

HttpURLConnection sending a POST request
/** * Send POST request via HttpURLConnection * * @param username * @param password * @return */public static String loginbypost (stri ng username, string password) {string path = "Http://192.168.0.107:8080/WebTest/LoginServerlet"; try {URL url = new URL (pat h); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("POST"); Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); String data = "Username=" + username + "&password=" + password;conn.setrequestproperty ("Content-length", data.length () + "");//post mode, in fact, the browser to the data to the server Conn.setdooutput (TRUE); Set the output stream outputstream OS = Conn.getoutputstream (); Gets the output stream Os.write (Data.getbytes ()); Write data to server int code = Conn.getresponsecode (); if (code = =) {InputStream is = Conn.getinputstream (); return STREAMTOOLS.S Treamtostring (IS);} else {return "network access Failed";}} catch (Exception e) {e.printstacktrace (); return "network access Failed";}}

HttpClient HttpClient is the Java Request Network framework provided by the open source organization Apache, which was originally created to facilitate the development of Java servers, and was packaged and simplified for HttpURLConnection APIs in the JDK. Improves performance and reduces the complexity of calling APIs, so Android has introduced this networking framework, and we don't need to import any jars or libraries to use directly, and it's worth noting that Android has officially announced that it's not recommended to use HttpClient. We should try to use less when we develop it, but it doesn't hurt to use it!
HttpClient sending a GET request

1, create the HttpClient object

2, create HttpGet object, specify request address (with parameter)

3, use HttpClient's Execute (), method to execute HttpGet request, get HttpResponse object

4, call HttpResponse's Getstatusline (). Getstatuscode () method to get the response code

5, call the HttpResponse of the GetEntity (). GetContent () gets the input stream to get the data written back by the server

/** * Send GET request via HttpClient *  * @param username * @param password * @return */public static String Loginbyhttpclientget ( String username, string password) {string path = "Http://192.168.0.107:8080/WebTest/LoginServerlet?username=" + Username + "&password=" + password; HttpClient client = new Defaulthttpclient (); Turn on the network access client HttpGet HttpGet = new HttpGet (path); Wrap a GET request try {httpresponse response = Client.execute (httpget);//client execution request int code = Response.getstatusline (). Getstatuscode (); Get the response code if (code = =) {InputStream is = response.getentity (). getcontent ();//Get entity content string result = Streamtools.streamt Ostring (IS); byte-flow string return result; else {return "network access Failed";}} catch (Exception e) {e.printstacktrace (); return "network access Failed";}}

HttpClient sending a POST request

1, create the HttpClient object

2, create HttpPost object, specify request address

3, create list<namevaluepair>, to load parameters

4, call the Setentity () method of the HttpPost object, load a Urlencodedformentity object, carry the previously encapsulated parameters

5, execute HttpPost request using HttpClient's Execute () method, get HttpResponse Object

6, call HttpResponse's Getstatusline (). Getstatuscode () method to get the response code

7, call the HttpResponse of the GetEntity (). GetContent () gets the input stream to get the data written back by the server

/** * Send POST request via HttpClient * * @param username * @param password * @return */public static String loginbyhttpclientpost (S Tring Username, string password) {string path = "Http://192.168.0.107:8080/WebTest/LoginServerlet"; try {HttpClient Client = new Defaulthttpclient (); Establish a client HttpPost HttpPost = new HttpPost (path); Package POST request//Set the entity parameter sent list<namevaluepair> parameters = new arraylist<namevaluepair> ();p Arameters.add ( New Basicnamevaluepair ("username", username));p arameters.add (New Basicnamevaluepair ("password", password)); Httppost.setentity (new urlencodedformentity (Parameters, "UTF-8")); HttpResponse response = Client.execute (HttpPost); Executes the POST request int code = Response.getstatusline (). Getstatuscode (); if (code = =) {InputStream is = response.getentity (). GE Tcontent (); String result = Streamtools.streamtostring (is); return result;} else {return "network access Failed";}} catch (Exception e) {e.printstacktrace (); return "failed to access Network";}}

Other open source networking framework Asynchttpclient In addition to the above-mentioned Android official recommended networking framework, in the open source world about the networking framework is really too much, such as afinal,xutils, and so on, are some open-source Daniel's own packaged networking framework, And in the GitHub open source community can be downloaded to, in fact, similar open source networking framework is basically based on httpurlconnection further encapsulation, greatly improve the performance, while simplifying the use of methods, here using Asynchttpclient as a case,        Other networking framework you can go to the Internet to find, download and try to use. Asynchttpclient is a very good networking framework that not only supports all HTTP requests, but also supports file uploads and downloads, and it takes time and effort to write a file to upload and download sound functions with HttpURLConnection. Because the request head is too many, the slightest careless will write wrong.        But Asynchttpclient has encapsulated these "trouble", we only need to download to asynchttpclient jar package or source code import project, Http, upload, download and so on, only need a few simple API to get it done. Asynchttpclient's GitHub homepage:https://github.com/AsyncHttpClient/async-http-client/Asynchttpclient sending a GET request

1, copy the downloaded source code to the SRC directory.

2, create an Asynchttpclient object

3, call the Get method of the class to send a GET request, incoming request resource address URL, create Asynchttpresponsehandler object

4, rewrite the two methods under Asynchttpresponsehandler, Onsuccess and OnFailure methods

/** * Send GET request via asynchttpclient */public void Loginbyasynchttpget () {String path = "http://192.168.0.107:8080/WebTest/ Loginserverlet?username=zhangsan&password=123 "; Asynchttpclient client = new Asynchttpclient (); Client.get (Path, new Asynchttpresponsehandler () {@Overridepublic void onfailure (int arg0, header[] arg1, byte[] arg2,throwable arg3) {//TODO auto-generated method stublog.i ("TAG", "Request failed:" + N EW String (ARG2));} @Overridepublic void onsuccess (int arg0, header[] arg1, byte[] arg2) {//TODO auto-generated method stublog.i ("TAG", "Request succeeded : "+ new String (ARG2));}});

Asynchttpclient sending a POST request

1, copy the downloaded source code to the SRC directory.

2, create an Asynchttpclient object

3, create request parameter, Requestparams object

4, call the Post method of the class post, incoming request resource address URL, request parameter requestparams, create Asynchttpresponsehandler Object

5, rewrite the two methods under Asynchttpresponsehandler, Onsuccess and OnFailure methods

/** * Send POST request via asynchttpclient */public void Loginbyasynchttppost () {String path = "http://192.168.0.107:8080/WebTest/ Loginserverlet "; Asynchttpclient client = new Asynchttpclient (); Requestparams params = new Requestparams ();p arams.put ("username", "Zhangsan");p arams.put ("password", "123"); Client.post (path, params, new Asynchttpresponsehandler () {@Overridepublic void onfailure (int arg0, header[] arg1, byte[] Arg2,throwable arg3) {//TODO auto-generated method stublog.i ("TAG", "Request failed:" + new String (ARG2));} @Overridepublic void onsuccess (int arg0, header[] arg1, byte[] arg2) {//TODO auto-generated method stublog.i ("TAG", "Request succeeded : "+ new String (ARG2));}});
Asynchttpclient Uploading Files

1, copy the downloaded source code to the SRC directory.

2, create an Asynchttpclient object

3, create request parameter, Requestparams object, request parameter contains only file object, for example:

Params.put ("Profile_picture", New File ("/sdcard/pictures/pic.jpg"));

4, call the Post method of the class post, incoming request resource address URL, request parameter requestparams, create Asynchttpresponsehandler Object

5, rewrite the two methods under Asynchttpresponsehandler, Onsuccess and OnFailure methods


Determine Network connection Status

Many times for handheld devices such as mobile phones or tablets, we do not know their network connection status, in the Internet, we must ensure that the device network is normal, whether we can connect to the Internet, or we are doing a lot of data upload or download, such as downloading network video, watching internet TV and so on, We have to save money for users, so big data transmission is obviously not using the user's expensive data traffic, but to determine whether the current network is under WiFi, using WiFi to carry out big data transmission, will give users a better experience, then the following tool class is used to determine the device network connection status, Not only the current setting of the mobile network under the WiFi environment, but also if the mobile network needs to set up the operator's proxy IP and port.

/** * Tool class for judging network status * */public class Networkutil {/* code IP */private static String proxy_ip = null;/* Proxy port */private static I NT Proxy_port = 0;/** * Determine if there is currently a network connection * * @param context * @return */public static Boolean isnetwork (context context) {bool EAN network = Iswifi (context), Boolean mobilework = IsMobile (context), if (!network &&!mobilework) {//No network connection LOG.I ( "Networkutil", "No Internet link!" "); return false;} else if (Network = = True && Mobilework = = False) {//WiFi connection log.i ("Networkutil", "WiFi connection! ");} else {//Network connection LOG.I ("Networkutil", "mobile network connection, read proxy information!") "); Readproxy (context); Read proxy information return true;} return true;} /** * Read Network proxy * * @param context */private static void Readproxy (context context) {URI uri = uri.parse ("Content://telephon Y/CARRIERS/PREFERAPN "); Contentresolver resolver = Context.getcontentresolver (); cursor cursor = resolver.query (URI, NULL, NULL, NULL, NULL); if (cursor! = NULL && Cursor.movetofirst ()) {PROXY_IP = Cursor.getstring (Cursor.getcolumnindex ("proxy")); Proxy_port = Cursor.getint (Cursor.getcolumnindex ("port"));} Cursor.close ();} /** * Determine if the current network is a WiFi LAN * * @param context * @return */public static Boolean Iswifi (context context) {Connectivitymanager Manager = (Connectivitymanager) context.getsystemservice (Context.connectivity_service); Networkinfo info = manager.getnetworkinfo (Connectivitymanager.type_wifi), if (info! = null) {return info.isconnected (); Returns the network connection status}return false; /** * Determine if the current network is a mobile network * * @param context * @return */public static Boolean IsMobile (context context) {Connectivitymanager m Anager = (Connectivitymanager) context.getsystemservice (Context.connectivity_service); Networkinfo info = manager.getnetworkinfo (connectivitymanager.type_mobile), if (info! = null) {return info.isconnected ( ); Returns the network connection status}return false;}}

Android Development Request Network Way detailed

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.