Network operations in Android (HttpURLConnection)

segmentfault's support for mackdown syntax is not very good, some pictures can't be displayed, you can go to my nuggets to check This article.

1. Introduction to Android network knowledge

The most important module of the Android program is the network part. How to download data from the network and how to upload the processed data to the network is often the key link of the Android program. There are many useful frameworks for network operations in Android, such as OkHttp, Velloy, Retrofit, etc. But today we will focus on the abstract class HttpURLConnection.

2. Use HttpURLConnection to implement Get and Post requests

1. Permission application

To do network-related operations in Android, you must apply for network permissions in the manifest file, as shown below:

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

Before Android 9.0, you only need to add this sentence to the manifest file, but Android 9.0 restricts http requests, so the above sentence is not enough. In order to lift this restriction, we need to create a security profile, the specific steps are as follows:

  1. Create xml/network-security-config file under res folder

  1. Add cleartextTrafficPermitted property

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
       <base-config cleartextTrafficPermitted="true"/>
    </network-security-config>
  2. Apply in the Application node of AndroidManifest.xml

    android:networkSecurityConfig="@xml/network_security_config"

2. get request

we start from play Android Find any API for a GET request above. The json data format is as follows:

Now let's use the GET request of HttpURLConnection to print out the above json data. The specific code is as follows:

 private final String URL = "https://wanandroid.com/wxarticle/chapters/json";
 
 // HttpURLConnection
private void get() {
    try {
        // 1. Instantiate a URL object
        URL url = new URL(URL);
        // 2. Get the HttpURLConnection instance
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 3. Set the properties related to the request
        // request method
        conn.setRequestMethod("GET");
        // request timeout
        conn.setConnectTimeout(10 * 1000);
        // 4. Get the response code 200: Success 404: The specified resource was not requested 500: The server is abnormal
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 5. Determine the response code and get the response data (the body of the response)
            // Get a stream of responses

            // IO operation
            InputStream in = conn.getInputStream();
            byte[] b = new byte[1024];
            int len;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = in.read(b)) > -1) {
                baos.write(b, 0, len);
            }
            String msg = baos.toString();
            Log.e("MainActivityTAG", msg);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void myClick(View v) {
    switch (v.getId()) {
        // After Android 4.0, network operations must be placed in child threads
        case R.id.btn_get:
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    get();
                }
            }.start();
            break;
    }
}

The data on the console is as follows, and we have successfully printed it out.

With the above code, we need to pay attention to three points:

  1. Apply for INTERNET permission in manifest file
  2. If it is an http request, you need to create a security configuration file network-security-config
  3. After Android 4.0, network operations must be placed in child threads

3. post request

we start from play Android Find an API for a POST request above. Then we can use the POST request of HttpURLConnection to implement a login function.

The specific code implementation is as follows:

private void post(String account, String password) {
    try {
        // 1. Instantiate a URL object
        URL url = new URL("https://www.wanandroid.com/user/login");
        // 2. Get the HttpURLConnection instance
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 3. Set the properties related to the request
        // request method
        conn.setRequestMethod("POST");
        // request timeout
        conn.setConnectTimeout(10 * 1000);
        // set allow output
        conn.setDoOutput(true);
        // Set the type of submitted data
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //Get the output stream (request body)
        OutputStream out = conn.getOutputStream();
        //write data
        out.write(("username=" + account + "&password=" + password).getBytes());

        //4. Get the response code 200: Success 404: The specified resource was not requested 500: The server is abnormal
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            //5. Determine the response code and get the response data (the body of the response)
            //Get a stream of responses
            InputStream in = conn.getInputStream();
            byte[] b = new byte[1024];
            int len;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //Read input stream in loop
            // in.read(b); // The return value of this method is int type data, which represents the length of the data actually read
            while ((len = in.read(b)) > -1) {
                //Store/write the contents of the byte array to the buffer stream
                //Parameter 1: Array to be written
                //Parameter 2: starting point
                //Parameter 3: length
                baos.write(b, 0, len);
            }
            String msg = new String(baos.toByteArray());

            Log.e("MainActivityTAG", msg);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void myClick(View v) {
    switch (v.getId()) {
        // After Android 4.0, network operations must be placed in child threads
        case R.id.btn_post:
            final String account = etAccount.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    post(account, password);
                }
            }.start();
            break;
    }
}

The data on the console is as follows, we have successfully logged in.

3. JSON data parsing

Json is a lightweight data interaction format with good readability and easy to write quickly. The mainstream end of the industry provides it with a complete solution (somewhat similar to regular expressions, which is supported by most languages ‚Äč‚Äčtoday), so that data can be exchanged between different platforms.

1. Parse using JSONObject


Now we need to parse the string "Guo Lin" from the above JSON data. How to use JSONObject?

The specific analysis method is as follows:

JSONObject jsonObject = new JSONObject(str);
final int errorCode = jsonObject.getInt("errorCode");
final String errorMsg = jsonObject.getString("errorMsg");
final String name = jsonObject.getJSONArray("data").getJSONObject(1).getString("name");

First get the data list, then get the second object, and get the value corresponding to the name attribute in the second object.

The specific effect is as follows:

The complete code is as follows:

private void paresByJSONObject() {
    new Thread(){
        @Override
        public void run() {
            super.run();
            String str = get();
            // Parse
            // JSONObject
            // Parameters: Strings that meet the requirements of Json format
            try {
                if (str != null) {
                    JSONObject jsonObject = new JSONObject(str);
                    final int errorCode = jsonObject.getInt("errorCode");
                    final String errorMsg = jsonObject.getString("errorMsg");
                    final String name = jsonObject.getJSONArray("data").getJSONObject(1).getString("name");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv1.setText("errorCode: " + errorCode);
                            tv2.setText(name);
                        }
                    });

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

private String get() {
    try {
        // 1. Instantiate a URL object
        URL url = new URL("https://wanandroid.com/wxarticle/chapters/json");
        // 2. Get the HttpURLConnection instance
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 3. Set the properties related to the request
        // request method
        conn.setRequestMethod("GET");
        // request timeout
        conn.setConnectTimeout(10 * 1000);
        // 4. Get the response code 200: Success 404: The specified resource was not requested 500: The server is abnormal
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 5. Determine the response code and get the response data (the body of the response)
            // Get a stream of responses

            // IO operation
            InputStream in = conn.getInputStream();
            byte[] b = new byte[1024];
            int len;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = in.read(b)) > -1) {
                baos.write(b, 0, len);
            }
            return baos.toString();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

2. Parsing with GSON

As you can see, it is relatively troublesome to use JSONObject to parse json data, so we will not use JSONObject to parse it in our daily work. At present, the more popular json parsing tools are gson, jackson, fastjson, etc. Here we will pick gson to briefly explain it.

1), convert the object into a json string (toJson)


I am able to create an object Wxarticle from one of the JSON data above.

public class Wxarticle {

    private int courseId;
    private int id;
    private String name;
    private int order;
    private int parentChapterId;
    private boolean userControlSetTop;
    private int visible;

    public Wxarticle() {
    }

    public Wxarticle(int courseId, int id, String name, int order, int parentChapterId, boolean userControlSetTop, int visible) {
        this.courseId = courseId;
        this.id = id;
        this.name = name;
        this.order = order;
        this.parentChapterId = parentChapterId;
        this.userControlSetTop = userControlSetTop;
        this.visible = visible;
    }

    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public int getParentChapterId() {
        return parentChapterId;
    }

    public void setParentChapterId(int parentChapterId) {
        this.parentChapterId = parentChapterId;
    }

    public boolean isUserControlSetTop() {
        return userControlSetTop;
    }

    public void setUserControlSetTop(boolean userControlSetTop) {
        this.userControlSetTop = userControlSetTop;
    }

    public int getVisible() {
        return visible;
    }

    public void setVisible(int visible) {
        this.visible = visible;
    }

    @Override
    public String toString() {
        return "wxarticle{" +
                "courseId=" + courseId +
                ", id=" + id +
                ", name='" + name + '\'' +
                ", order=" + order +
                ", parentChapterId=" + parentChapterId +
                ", userControlSetTop=" + userControlSetTop +
                ", visible=" + visible +
                '}';
    }
}

Gson's toJson method is to convert an object into a Json string. Let's try calling this method.

Gson gson = new Gson();
// turn object into json string
Wxarticle wxarticle = new Wxarticle(13, 408, "Hongyang", 190000, 407, false, 1);
String str = gson.toJson(wxarticle);
Log.e("JSONActivity", str);

We can see that the object has been successfully converted into a Json string.

2), convert the json string into an object (fromJson)

We use the fromJson method to output the name in the above json object, we need to create a Test object, the specific code is as follows:

public class Test {

    private List<Wxarticle> data;
    private int errorCode;
    private String errorMsg;

    public Test() {
    }

    public Test(List<Wxarticle> data, int errorCode, String errorMsg) {
        this.data = data;
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public List<Wxarticle> getData() {
        return data;
    }

    public void setData(List<Wxarticle> data) {
        this.data = data;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

The specific parsing code is as follows:

 // fromJson
new Thread(){
    @Override
    public void run() {
        super.run();
        String str = get();
        Test test = gson.fromJson(str, Test.class);
        for (int i = 0; i < test.getData().size(); i++) {
            Log.e("JSONActivityTag", test.getData().get(i).getName() + "");
        }
    }
}.start();

As shown below, we have successfully parsed all the names in the json data.

Fourth, the project source code

Project source code download link . Directly download the project to the local and then import it to run directly. All the above API s are passed through play Android obtained.

Tags: Android network

Posted by jamesxg1 on Sun, 15 May 2022 06:18:56 +0300