Android development request network

Source: Internet
Author: User
Tags response code

Android development request network

 

We all know that the Android mobile operating system supported and released by Google is mainly used to quickly occupy the market share of the mobile Internet. The so-called mobile Internet is also the Internet, of course, any software involving the Internet is indispensable for the development of the Internet module. It is true that Android Internet development is also a crucial part of our development. How does Android perform online operations? This blog briefly introduces common Android networking methods, including HttpUrlConnection supported by JDK, HttpClient supported by Apache, and some open-source networking frameworks (such as AsyncHttpClient. This blog only describes the implementation process and method, without explaining the Principles. Otherwise, it is difficult to clarify the principles in words. In fact, we know how to use them to solve some basic development needs.

The vast majority of Android applications are connected over Http, and few are Socket-based. Here we will mainly explain how to connect to the Internet based on Http. The instance is created in a simulated login module. The login request data only contains two simple fields: username and password.

 

HttpUrlConnectionHttpUrlConnection is the online API provided by JDK. We know that the Android SDK is based on Java, so of course we should give priority to HttpUrlConnection, the most primitive and basic API, in fact, most open-source networking frameworks are basically encapsulated based on JDK's HttpUrlConnection. The following steps are required to master HttpUrlConnection:

1. Convert the access path to a URL.

 

URL url = new URL(path);

 

2. Get the connection through URL.

 

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

 

3. Set the request method.

 

conn.setRequestMethod(GET);

 

4. Set the connection timeout.

 

conn.setConnectTimeout(5000);

 

5. Set 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. Perform different operations for different response codes

7.1, Request Code 200, indicating that the request is successful, get the input stream of the returned content

 

InputStream is = conn.getInputStream();

 

7.2, convert the input stream to string Information

 

Public class StreamTools {/*** convert the input stream to a String ** @ param is * The input stream obtained from the Network * @ return */public static String streamToString (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 400 is returned, a network exception is returned and a response is made.

 

HttpUrlConnection sends a GET request

 

/*** Send a GET request through HttpUrlConnection ** @ param username * @ param password * @ return */public static String loginByGet (String 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 = 200) {InputStream is = conn. getInputStream (); // convert byte streams to return StreamTools. streamToString (is);} else {return Network Access failed;} catch (Exception e) {e. printStackTrace (); return Network Access failed ;}}

 

HttpUrlConnection sends a POST request
/*** Send a POST request through HttpUrlConnection ** @ param username * @ param password * @ return */public static String loginByPost (String username, String password) {String path = http: // 192.168.0.107: 8080/WebTest/LoginServerlet; try {URL url = new URL (path); 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 () +); // the POST method means that the browser writes 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 the server int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); return StreamTools. streamToString (is);} else {return Network Access failed;} catch (Exception e) {e. printStackTrace (); return Network Access failed ;}}

HttpClientHttpClient is a Java request network framework provided by Apache, an open-source organization. It was first created to facilitate Java Server development. It encapsulates and simplifies the HttpUrlConnection APIs in JDK, this improves performance and reduces the hassle of calling APIs. Android also introduces this network framework, which can be directly used without importing any jar or class libraries, it is worth noting that the Android official has announced that HttpClient is not recommended. We should try to use it as little as possible during development, but it will be okay if we use it!
HttpClient sends a GET request

1. Create an HttpClient object

2. Create an HttpGet object and specify the request address (with parameters)

3. Use execute () of HttpClient to execute the HttpGet request and obtain the HttpResponse object.

4. Call the getStatusLine (). getStatusCode () method of HttpResponse to obtain the response code.

5. Call HttpResponse's getEntity (). getContent () to get the input stream and data written back by the server.

/*** Send a GET request through 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 (); // enable the network access client HttpGet httpGet = new HttpGet (path ); // wrap a GET request try {HttpResponse response = client.exe cute (httpGet); // The client executes the request int code = response. getStatusLine (). getStatusCode (); // get the response code if (code = 200) {InputStream is = response. getEntity (). getContent (); // get the object content String result = StreamTools. streamToString (is); // byte stream string return result;} else {return Network Access failed;} catch (Exception e) {e. printStackTrace (); return Network Access failed ;}}

HttpClient sends a POST request

1. Create an HttpClient object

2. Create an HttpPost object and specify the request address

3. Create a List To load parameters.

4. Call the setEntity () method of the HttpPost object, load a UrlEncodedFormEntity object, and carry the previously encapsulated parameters.

5. Use the execute () method of HttpClient to execute the HttpPost request and obtain the HttpResponse object.

6. Call the getStatusLine (). getStatusCode () method of HttpResponse to obtain the response code.

7. Call HttpResponse's getEntity (). getContent () to get the input stream and data written back by the server.

/*** Send a POST request through HttpClient ** @ param username * @ param password * @ return */public static String loginByHttpClientPOST (String username, String password) {String path = http: /// 192.168.0.107: 8080/WebTest/LoginServerlet; try {HttpClient client = new DefaultHttpClient (); // create a client HttpPost httpPost = new HttpPost (path ); // wrap the POST request // set the object parameter List to be sent
 
  
Parameters = new ArrayList
  
   
(); Parameters. add (new BasicNameValuePair (username, username); parameters. add (new BasicNameValuePair (password, password); httpPost. setEntity (new UrlEncodedFormEntity (parameters, UTF-8); HttpResponse response = client.exe cute (httpPost); // execute the POST request int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). getContent (); String result = StreamTools. streamToString (is); return result;} else {return Network Access failed;} catch (Exception e) {e. printStackTrace (); return failed to access the network ;}}
  
 

Other open-source networking frameworks, AsyncHttpClient, apart from the networking frameworks officially recommended by Android, have too many online frameworks in the open-source world, such as afinal and xutils, these are some open-source network frameworks encapsulated by Daniel and can be downloaded in the GitHub open-source community. In fact, similar open-source network frameworks are basically further encapsulated based on HttpUrlConnection, greatly improving performance, at the same time, it simplifies the use of methods. Here we use AsyncHttpClient as a case. You can find other network frameworks online and download and try it. AsyncHttpClient is an excellent networking framework that not only supports all Http requests, but also supports file upload and download, it takes a certain amount of time and effort to use HttpUrlConnection to write a complete file upload and download function, because there are too many request headers and errors may occur if you are careful. However, AsyncHttpClient has encapsulated these "troubles". We only need to download the jar package or source code to the AsyncHttpClient import project, Http, upload, download, and so on, you only need a few simple APIs. AsyncHttpClient GitHub homepage: https://github.com/asynchttpclient/async-http-client/asynchttpclientsend getrequest

1. Copy the downloaded source code to the src directory.

2. Create an AsyncHttpClient object

3. Call the get method of this class to send a GET request, pass in the request resource Address URL, and create an AsyncHttpResponseHandler object.

4. Rewrite the two methods under AsyncHttpResponseHandler: onSuccess and onFailure.

 

/*** 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: + new String (arg2) ;}@ Overridepublic void onSuccess (int arg0, Header [] arg1, byte [] arg2) {// TODO Auto-generated method stubLog. I (TAG, request successful: + new String (arg2 ));}});}

 

AsyncHttpClient sends a POST request

1. Copy the downloaded source code to the src directory.

2. Create an AsyncHttpClient object

3. Create a request parameter and a RequestParams object

4. Call the post method of this class to send a POST, pass in the request resource Address URL, request parameter RequestParams, and create the AsyncHttpResponseHandler object

5. Rewrite the two methods under AsyncHttpResponseHandler: onSuccess and onFailure.

/*** Send POST request via AsyncHttpClient */public void publish () {String path = http: // 192.168.0.107: 8080/WebTest/LoginServerlet; AsyncHttpClient client = new AsyncHttpClient (); requestParams params = new RequestParams (); params. put (username, zhangsan); params. put (passwords, 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 successful: + new String (arg2 ));}});}
AsyncHttpClient uploads files

1. Copy the downloaded source code to the src directory.

2. Create an AsyncHttpClient object

3. Create a request parameter and a RequestParams object. The request parameter only contains the file object. For example:

 

params.put(profile_picture, new File(/sdcard/pictures/pic.jpg));

 

4. Call the post method of this class to send a POST, pass in the request resource Address URL, request parameter RequestParams, and create the AsyncHttpResponseHandler object

5. Rewrite the two methods under AsyncHttpResponseHandler: onSuccess and onFailure.

 

Determine the network connection status

In many cases, we do not know the network connection status of handheld devices such as mobile phones or tablets. When connected, we must ensure that the network of the devices is normal, whether it can be connected to the Internet, or if we are uploading or downloading a large amount of data, such as downloading online videos or watching online TV, we must save money for users, in this way, big data transmission obviously does not allow users to use expensive data traffic. Instead, it determines whether the current network is connected to wi-fi and uses wifi for big data transmission, this tool class is used to determine the network connection status of the device. It not only determines whether the current mobile phone network is set to WiFi, in addition, if the mobile phone network also needs to set the carrier's proxy IP address and port.

 

/*** Tool class for determining the network status **/public class NetworkUtil {/* Code IP */private static String PROXY_IP = null; /* proxy port */private static int PROXY_PORT = 0; /*** determine whether a network connection exists ** @ param context * @ return */public static boolean isNetwork (Context context) {boolean network = isWifi (context ); boolean mobilework = isMobile (context); if (! Network &&! Mobilework) {// No network connection Log. I (NetworkUtil, no network connection !); 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;}/*** read network proxy ** @ param context */private static void readProxy (Context context) {Uri uri = Uri. parse (content: // telephony/carriers/preferapn); ContentResolver resolver = context. getContentResolver (); Cursor cursor = resolver. query (uri, null, null); if (cursor! = Null & cursor. moveToFirst () {PROXY_IP = cursor. getString (cursor. getColumnIndex (proxy); PROXY_PORT = cursor. getInt (cursor. getColumnIndex (port);} cursor. close ();}/*** determine whether the current network is a Wi-Fi LAN ** @ param context * @ return */public static boolean isWifi (Context context) {ConnectivityManager manager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo = manager. ge TNetworkInfo (ConnectivityManager. TYPE_WIFI); if (info! = Null) {return info. isConnected (); // returns the network connection status} return false ;} /*** determine whether the current network is a mobile network ** @ param context * @ return */public static boolean isMobile (Context context) {ConnectivityManager manager = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo = manager. getNetworkInfo (ConnectivityManager. TYPE_MOBILE); if (info! = Null) {return info. isConnected (); // returns the network connection status} return false ;}}

 

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.