Android - Section 9 network programming

Posted by stef686 on Wed, 02 Mar 2022 16:53:33 +0100

1, Network access overview

Let's explain and review. We learned Android's UI, various layouts and controls before. In fact, when we work in the future, this UI does not need us to design. A designer will design the UI for us, and then we will restore the UI in the form of code in xml file. For example, the following figure is the data card interface in qq, After we have designed the UI, let me take the text control as an example. The text data in it can be represented by a string of numbers (false data) to indicate that it is a control. The text data in it can be set through activity, but we know that all app s we use have different data for different users. So how can we obtain this data? We can get data from the server by sending a request, and the server queries the database and returns the data to Android.

Before network programming, we need to make preparations

Turn on network access

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

http request data is generally not encrypted
https is generally encrypted
Https access is safer than HTTP, so android only allows us to use the Https protocol by default. If necessary, you can turn on HTTP access.

android:usesCleartextTraffic="true"

2, Accessing data via Http

1.MainActivity.java core code:

try {
            URL url=new URL("http://148.70.46.9/user "); / / get the server address
            HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();//Both parties establish connection

            urlConnection.setRequestMethod("GET");//Send request to server

            //The data returned by the server is text, so the returned data is byte stream by default
            InputStream inputStream=urlConnection.getInputStream(); //Byte stream
            Reader reader=new InputStreamReader(inputStream); //Convert byte stream into character stream
            BufferedReader bufferedReader=new BufferedReader(reader);//Characters are transferred into a buffer stream and can be read one line at a time

            String result = "";
            String temp;
            while ((temp=bufferedReader.readLine())!=null){//When the data read by temp is empty, it ends
                result += temp;
                Log.i("Main","result :"+result);
            }
            inputStream.close();
            reader.close();
            bufferedReader.close();
            //todo close flow
        } catch (Exception e) {
            e.printStackTrace();
        }


2. Android.com will report an error after running os. NetworkOnMainThreadException

This error indicates that the network is abnormal in the main thread. Network access cannot be in the main thread.

So we need to create a thread.
3. Create thread
code:

	Thread thread = new Thread(){//Method 1
	@Override
	public void run() {
	super.run();
	//Child thread
	}
	};
	thread.start();

Put the sending request and receiving server data code into the sub thread
4. Final code:

package com.hnucm.a_test10;


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread thread = new Thread(){//Method 1
            @Override
            public void run() {
                super.run();
                //Child thread
                try {
                    URL url=new URL("http://148.70.46.9/user "); / / get the server address
                    HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();//Both parties establish connection

                    urlConnection.setRequestMethod("GET");//Send request to server

                    //The data returned by the server is text, so the returned data is byte stream by default
                    InputStream inputStream=urlConnection.getInputStream(); //Byte stream
                    Reader reader=new InputStreamReader(inputStream); //Convert byte stream into character stream
                    BufferedReader bufferedReader=new BufferedReader(reader);//Characters are transferred into a buffer stream and can be read one line at a time

                    String result = "";
                    String temp;
                    while ((temp=bufferedReader.readLine())!=null){//When the data read by temp is empty, it ends
                        result += temp;
                        Log.i("Main","result :"+result);
                    }
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                    //todo close flow
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();


    }
}

5. Get TextView control and assign value to the result


Because in android, UI operations, control settings, properties and click events cannot be executed in the child thread, but only in the main thread

So modify the above code

Final code:
package com.hnucm.a_test10;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.awt.font.TextAttribute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.tv);
        textView.setText("initialization");
        Thread thread = new Thread(){//Method 1
            @Override
            public void run() {
                super.run();
                //Child thread
                try {
                    //    URL url=new URL("http://www.baidu.com "); / / this is the domain name
                    URL url=new URL("http://148.70.46.9/user "); / / get the server address
                    HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();//Both parties establish connection

                    urlConnection.setRequestMethod("GET");//Send request to server

                    //The data returned by the server is text, so the returned data is byte stream by default
                    InputStream inputStream=urlConnection.getInputStream(); //Byte stream
                    Reader reader=new InputStreamReader(inputStream); //Convert byte stream into character stream
                    BufferedReader bufferedReader=new BufferedReader(reader);//Characters are transferred into a buffer stream and can be read one line at a time

                    String temp;
                    while ((temp=bufferedReader.readLine())!=null){//When the data read by temp is empty, it ends
                        Log.i("Main","temp :"+temp);
                        Thread.sleep(2000);//The simulated network request takes a long time
                        String finalResult=temp;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    textView.setText(finalResult);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });


                    }
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                    //todo close flow
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }
}


3, Method for obtaining multiple values through network

Method 1: cut the string

Some irrelevant characters can be added to the data to be received to facilitate cutting
For example:
Today is Tuesday. It's sunny
Cut the string through the split("test") method
However, this method has great disadvantages and is inconvenient, and if the field contains test, it will cut the error

Method 2: xml structure

Will be based on
<>text</>This structure resolves to the field name

Get the value by parsing xml, but this method is also less used now

Method 3: parse through json
For example, the above example is represented by json:
"Today is" "Tuesday" "the weather is fine"

The biggest advantage of json parsing over xml structure is that json data structure is shorter than xml, so the shorter the overall field returned, the less traffic we consume in transmission. Another reason is that json is simpler

Topics: Java Android Android Studio