preface

I recently came up with the idea of doing an in-depth analysis of the main Android open source framework, and then writing a series of articles, including detailed usage and source code analysis of the framework. The purpose is to understand the underlying principle of the framework by appreciating the source code of god, that is, to do not only know it, but also know why.

Here I say their own experience reading source code, I generally in accordance with the peacetime use of a framework or a system source code process, first of all to know how to use, and then go to the bottom of each step to do what, with what good design patterns, why so design.

Series of articles:

  • Android mainstream open source framework (a) OkHttp -HttpClient and HttpURLConnection use details
  • Android main open source framework (ii) OkHttp usage details
  • Android mainstream open source framework (three) OkHttp source code analysis
  • Android mainstream open source framework (iv) Retrofit usage details
  • Android mainstream open source framework (v) Retrofit source code analysis
  • Android mainstream open source framework (six) Glide execution process source code analysis
  • More frameworks continue to be updated…

Check out AndroidNotes for more dry stuff

HttpClient and HttpURLConnection

1.1 HttpClient

HttpClient is an open source library provided by Apache that can be used to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol. The Android SDK originally included HttpClient, but Google in Android version 6.0 has removed the library related code, can only rely on the library to use.

1.2 HttpURLConnection

HttpURLConnection is a java.net package that provides basic functions for accessing HTTP. It inherits from URLConnection and can be used to send GET and POST requests to specified websites. HttpURLConnection has no encapsulation compared to HttpClient, but because of this we can extend it more easily.

Prior to Android 2.2, however, HttpURLConnection had some annoying bugs. For example, calling the close() method on a readable InputStream might cause the connection pool to fail. The usual solution is to disable connection pooling as follows:

private void disableConnectionReuseIfNecessary(a) {
      // This is a pre-2.2 bug
      if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive"."false"); }}Copy the code

Use HttpClient

2.1 Preparations before Use

  1. Add Network Permission
<uses-permission android:name="android.permission.INTERNET"/>
Copy the code
  1. If you are using Android Studio, you need to add the following to build.gradle in the module you are using:
android {
    useLibrary 'org.apache.http.legacy'
}
Copy the code
  1. As of Android 9, the library has been removed from bootCLASspath and is not available for applications by default.

To continue using the Apache HTTP client, applications targeting Android 9 and later can add the following to their Androidmanifest.xml application node (see Apache HTTP Client deprecation) :

<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Copy the code

2.2 GET Requests from HttpClient

The usage process is described in detail in the comments, with the following code:

    private void getRequestByHttpClient(a) {
        //1. Create an HttpClient object using DefaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        //2. Create a request object (in this case a GET request) with the request address
        HttpGet httpGet = new HttpGet("https://www.baidu.com");
        try {
            //3. Call the execute method of the HttpClient object to send the request and return HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //4. Check whether the request is successful. Status code 200 indicates that the request is successful
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                //5. Call the getContent method of the HttpEntity object to get the input stream of the response data
                InputStream inputStream = httpResponse.getEntity().getContent();
                //6. Convert the input stream to a string
                String data = inputStream2String(inputStream);
                Log.i(TAG, "data: "+ data); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

The inputStream2String method is as follows:

    private String inputStream2String(InputStream inputStream) {
        String data = "";
        BufferedReader bufferedReader = null;
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while((line = bufferedReader.readLine()) ! =null) {
                stringBuilder.append(line).append("\n");
            }
            data = stringBuilder.toString();
            if(! TextUtils.isEmpty(data)) {// Remove the last superfluous newline character
                data = data.substring(0, data.length() - 1); }}catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(bufferedReader ! =null) { bufferedReader.close(); }}catch(IOException e) { e.printStackTrace(); }}return data;
    }
Copy the code

The network request should be called in the child thread, as follows:

        new Thread(new Runnable() {
            @Override
            public void run(a) {
                getRequestByHttpClient();
            }
        }).start();
Copy the code

The print result is as follows:

<! DOCTYPE html> <! --STATUS OK--><html> <head><meta http-equiv=content-type content=text/html; charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css></title> </head> <body link=#0000cc> </body> </html>Copy the code

2.3 POST Requests from the HttpClient

A POST request is similar to a GET request, except that the request object HttpGet is replaced with HttpPost, and the request parameters are set with the setEntity method of HttpPost. The usage process is described in detail in the comments, with the following code:

    private void postRequestByHttpClient(a) {
        //1. Create an HttpClient object using DefaultHttpClient
        HttpClient httpClient = new DefaultHttpClient();
        // Create a request object (POST request) with the request address (postman)
        HttpPost httpPost = new HttpPost("https://postman-echo.com/post");
        try {
            //3. Call the setEntity method of the HttpPost object to set the required parameters
            List<NameValuePair> postParams = new ArrayList<>();
            postParams.add(new BasicNameValuePair("username"."wildma"));
            postParams.add(new BasicNameValuePair("password"."123456"));
            httpPost.setEntity(new UrlEncodedFormEntity(postParams));

            //4. Call the execute method of the HttpClient object to send the request and return HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //5. Check whether the request is successful. Status code 200 indicates that the request is successful
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                //6. Call the getContent method of the HttpEntity object to get the input stream of the response data
                InputStream inputStream = httpResponse.getEntity().getContent();
                //7. Convert the input stream to a string
                String data = inputStream2String(inputStream);
                Log.i(TAG, "data: "+ data); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

Calling this method in a child thread prints the following:

{
 "args": {},
 "data": ""."files": {},
 "form": {
  "username": "wildma"."password": "123456"
 },
 "headers": {
  "x-forwarded-proto": "https"."host": "postman-echo.com"."content-length": "31"."content-type": "application/x-www-form-urlencoded"."user-agent": "Apache-HttpClient/UNAVAILABLE (java 1.4)"."x-forwarded-port": "443"
 },
 "json": {
  "username": "wildma"."password": "123456"
 },
 "url": "https://postman-echo.com/post"
}
Copy the code

HttpURLConnection

3.1 Preparations before Use

Add Network Permission

<uses-permission android:name="android.permission.INTERNET"/>
Copy the code

3.2 GET Request of HttpURLConnection

The usage process is described in detail in the comments, with the following code:

    private void getRequestByHttpURLConnection(a) {
        try {
            //1. Create URL objects
            URL url = new URL("https://www.baidu.com");
            //2. Call the openConnection method of the URL object to obtain the HttpURLConnection instance
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // set the request method (in this case GET request)
            httpURLConnection.setRequestMethod("GET");
            4 / / connection
            httpURLConnection.connect();
            //5. Check whether the request is successful. Status code 200 indicates that the request is successful
            if (httpURLConnection.getResponseCode() == 200) {
                //6. Call the getInputStream method of the HttpURLConnection object to get the input stream of the response data
                InputStream inputStream = httpURLConnection.getInputStream();
                //7. Convert the input stream to a string
                String data = inputStream2String(inputStream);
                Log.i(TAG, "data: "+ data); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

This method is called in a child thread and prints the same result as the HttpClient GET request.

3.3 POST Request of HttpURLConnection

The POST request is similar to the GET request except that you need to replace the request method GET with POST, and then set the request parameters through the output stream. You also need to set the allowed input and output, namely setDoInput(True) and setDoOutput(true). The usage process is described in detail in the comments, with the following code:

    private void postRequestByHttpURLConnection(a) {
        try {
            //1. Create URL objects
            URL url = new URL("https://postman-echo.com/post");
            //2. Call the openConnection method of the URL object to obtain the HttpURLConnection instance
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // set the request method (in this case POST request)
            httpURLConnection.setRequestMethod("POST");
            /*4. Set input/output */
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            /*5. Set request parameters */
            String params = new StringBuilder()
                    .append("username=" + URLEncoder.encode("wildma"."UTF-8"))
                    .append("&password=" + URLEncoder.encode("123456"."UTF-8")).toString();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(params.getBytes());
            outputStream.flush();
            outputStream.close();

            / / 6. Connections
            httpURLConnection.connect();
            //7. Check whether the request is successful. Status code 200 indicates that the request is successful
            if (httpURLConnection.getResponseCode() == 200) {
                Call the getInputStream method of the HttpURLConnection object to get the input stream of the response data
                InputStream inputStream = httpURLConnection.getInputStream();
                //9. Convert the input stream to a string
                String data = inputStream2String(inputStream);
                Log.i(TAG, "data: "+ data); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

This method is called in a child thread and prints the same result as the HttpClient POST request.

HttpClient and HttpURLConnection

Prior to Android 2.2, HttpClient was less buggy, so using it was the best choice.

For Android 2.3 and later, HttpURLConnection is the best choice. Its simple API and small size make it ideal for Android projects. The compression and caching mechanisms can effectively reduce network access traffic, improve speed and save power.

In fact, reference Google network framework Volley can also be concluded, Volley source code in Android 2.3 and above version, using HttpURLConnection, and in Android 2.2 and below version, HttpClient is used.

Five, the source

HttpClient and HttpURLConnection demo

About me

I am Wildma, CSDN certified blog expert, excellent author of Simple book programmer, good at screen adaptation. If the article is helpful to you, a “like” is the biggest recognition for me!