1. Write it in front
Most andriod applications need to interact with the server data. HTTP, FTP, SMTP or directly based on SOCKET programming can interact with data, but HTTP must be the most widely used protocol.
This article does not focus on the specific content of the HTTP protocol, but only discusses two ways to use the HTTP protocol to access the network in Android development - HttpURLConnection and HttpClient
Because you need to access the network, you need to add the following permissions
<uses-permission android:name="" />
2.1 GET method
import ; import ; import ; import ; import ; // The following code implements the HTTP request in GET mode// Connecting to the network is a time-consuming operation, and it is usually done by creating new threads. private void connectWithHttpURLConnection() { new Thread( new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { // Call the openConnection method of the URL object to get an instance of HttpURLConnection URL url = new URL("https://"); connection = (HttpURLConnection) (); // Set request method, GET or POST ("GET"); // Set the time for connection timeout and read timeout, in milliseconds (ms) (8000); (8000); // getInputStream method gets the input stream returned by the server InputStream in = (); // Use the BufferedReader object to read the returned data stream // Read by line and store in the StringBuider object response BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = ()) != null) { (line); } //.......... // The code for processing data is omitted here // If you need to update the UI, you need to pass the data back to the main thread. For details, you can search for Android multithreaded programming. } catch (Exception e){ (); } finally { if (connection != null){ // After ending, close the connection (); } } } }).start(); }
2.2 POST method
import ; //Change the corresponding part to("POST"); DataOutputStream data = new DataOutputStream(()); ("stu_no=12345&stu_name=Tom");
Passing multiple parameters for&Separate
If you need to pass in complex parameters, you can use JSON. For the introduction of JSON usage, you can refer to my other essay on JSON parsing two methods.
3.1 GET method
import ; import ; import ; import ; import ; import ; // Create a DefaultHttpClient instanceHttpClient httpClient = new DefaultHttpClient(); //Pass in the URL and executeHttpGet httpGet = new HttpGet("https://"); HttpResponse httpResponse = (httpGet); // The request result is determined by the status code.// Common status code 200 Request successful, 404 page not found// More status codes for HTTP are directly GOOGLEif (().getStatusCode() == HttpStatus.SC_OK) { // The request is successful, use HttpEntity to obtain the returned data // Use EntityUtils to convert the return data to a string HttpEntity entity = (); String response = (entity); //If it is Chinese, specify the encoding //==>String response = (entity, "utf-8"); }
3.2 POST method
import ; import ; import ; import ; import ; import ; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost("https://"); // Use NameValuePair (key value pair) to store parametersList<NameValuePair> data = new ArrayList<NameValuePair>(); // Add key-value pairs(new BasicNameValuePair("stu_no", 12345)); (new BasicNameValuePair("stu_name", "Tom")); // Use the setEntity method to pass in the encoded parameters(new UrlEncodedFormEntity(data, "utf-8")); // Execute the POST requestHttpResponse httpResponse = (httpPost); // ......Omit the code for processing httpResponse, which is consistent with the GET method
3.3 android 6.0 removes HttpClient
The SDK of Android 6.0 (API 23) version has removed the Apache HttpClient-related classes. The solution is GOOGLE by yourself. It is recommended to use HTTPURLConnection.
If you still need to use this class, click to view the solution.
Actual combat
If you have used JQuery (a javasript library), you must be impressed by JQuery's network programming, for example, an HTTP request only requires the following lines of code.
// JQuery's post method$.post("https://",{ "stu_no":12345, "stu_name":"Tom", }).done(function(){ //...Successful code requested }).fail(function(){ //...Request failed code }).always(function(){ //...Code that will always be executed })
Of course, we don’t want to write such cumbersome code in 2.1 every time we request, so can android HTTP requests be as simple as JQuery? sure! The following code implements the HTTP request method encapsulation of HttpURLConnection:
4.1 Define the interface HttpCallbackListener, in order to implement callbacks
// Define the HttpCallbackListener interface// Contains two methods, successful and failed callback function definitionspublic interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
4.2 Create HttpTool class, abstract request method (GET)
import ; import ; import ; import ; import ; /* Create a new class HttpTool to abstract public operations * In order to avoid instantiation when calling the sendRequest method, set it to a static method * Pass in HttpCallbackListener object for method callback * Because network requests are time-consuming, they are usually done in child threads. * In order to obtain the data returned by the server, you need to use the java callback mechanism */ public class HttpTool { public static void sendRequest(final String address, final HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); connection = (HttpURLConnection) (); ("GET"); (8000); (8000); InputStream in = (); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = ()) != null) { (line); } if (listener != null) { // Callback method onFinish() (()); } } catch (Exception e) { if (listener != null) { // Callback method onError() (e); } } finally { if (connection != null) { (); } } } }).start(); } }
4.3 Call Example
// Use this HttpTool to initiate a GET requestString url = "https://"; (url,new HttpCallbackListener(){ @Override public void onFinish(String response) { // ...Omit the processing code for the returned result } @Override public void onError(Exception e) { // ...Omit the processing code for request failure } });
4.4 Abstract request method (POST)
/* Add a parameter params based on the implementation of the GET method. * Convert the parameter to a string and pass it in * You can also pass in a collection of key-value pairs and then process */ public static void sendRequest(final String address, final String params, final HttpCallbackListener listener){ //... }
The above is all about this article, I hope it will be helpful to everyone's learning.