Android uses network technology, usage of WebView, usage of OkHttp, parsing XML format data (Pull, SAX), parsing JSON format data (JSONObject, GSON)

1. Usage of WebView

 <WebView
        android:id="@ + id/Web_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteX="165dp"
        tools:layout_editor_absoluteY="58dp" />
public class MainActivity extends AppCompatActivity {<!-- -->

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R. layout. activity_main);
        WebView webView = findViewById(R.id.Web_view);
        Button button = findViewById(R.id.button);

        //Let WebView support js script
        webView.getSettings().setJavaScriptEnabled(true);
        
        //When it is necessary to jump from one webpage to another, the target website is still displayed in WebView
        webView.setWebChromeClient(new WebChromeClient());


        //Click the button to open the web page in the application
        button.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View view) {<!-- -->
                // open url content
                webView.loadUrl("https://www.baidu.com");
                // make the button invisible
                button.setVisibility(View.INVISIBLE);
            }
        });
    }
}

2. Use OkHttp

1. ScrollView

Since the space of the mobile phone screen is generally relatively small, sometimes too much content cannot be displayed on one screen. With the help of the ScrollView control, we can scroll to view the part of the content outside the screen.

 <ScrollView
        android:id="@ + id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="88dp"
        tools:layout_editor_absoluteY="118dp">

        <TextView
            android:id="@ + id/textinput_suffix_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

2, runOnUiThread

private void showResponse(String str){<!-- -->
    runOnUiThread(new Runnable() {<!-- -->
        @Override
        public void run() {<!-- -->
            TextView textView = findViewById(R.id.textinput_suffix_text);
            textView.setText(str);
        }
    });
}

runOnUiThread is a method in Android that allows you to update the UI in a non-UI thread. In Android applications, UI elements (such as TextView, Button, etc.) can only be updated on the main thread (also known as the UI thread). If you try to update UI elements directly on a non-UI thread, exceptions and crashes will result.

3. GET request

image-20230731103112569

private void SendRequestWithOkHttp(){<!-- -->
    new Thread(new Runnable() {<!-- -->
        @Override
        public void run() {<!-- -->
            //Open okHttp
            OkHttpClient client = new OkHttpClient();
            //Registration request
            Request request = new Request.Builder().url("https://www.baidu.com").build();

            try {<!-- -->
                //Accept sending requests to the server
                Response response = client.newCall(request).execute();
                // Get the data of the message
                String responseData = response. body(). string();
                showResponse(responseData);
            } catch (IOException e) {<!-- -->
                throw new RuntimeException(e);
            }

        }
    }).start();
}

4. Post request

image-20230731103848563

private void SendRequestWithOkHttp(){<!-- -->
    new Thread(new Runnable() {<!-- -->
        @Override
        public void run() {<!-- -->
            //Open okHttp
            OkHttpClient client = new OkHttpClient();
            //Send build data
            RequestBody requestBody = new FormBody.Builder().add("uesr","admain").add("user","asdd").build();

            // Pass the sent data to the request
            Request request = new Request.Builder().url("https://baidu.com").post(requestBody).build();

            try {<!-- -->
                //Accept sending requests to the server
                Response response = client.newCall(request).execute();
                // Get the data of the message
                String = response. body(). string();
                showResponse(responseData);
            } catch (IOException e) {<!-- -->
                throw new RuntimeException(e);
            }

        }
    }).start();
}

3. Parsing XML format data

1. Pull analysis

private void parseXMlWithPull(String xmlData) {<!-- -->
    try {<!-- -->
        XmlPullParserFactory factory = XmlPullParserFactory. newInstance();
        XmlPullParser xmlPullParser = factory. newPullParser();

        //put in xml data for parsing
        xmlPullParser.setInput(new StringReader(xmlData));

        //Get the current parsing event
        int enventType = xmlPullParser. getEventType();
        String id = "";
        String name = "";
        String version = "";


        while (enventType != xmlPullParser.END_DOCUMENT) {<!-- -->
            String nodeName = xmlPullParser. getName();
            switch (enventType) {<!-- -->
                case START_TAG:
                    if ("id".equals(nodeName)) {<!-- -->
                        id = xmlPullParser. nextText();
                    }
                    if ("name".equals(nodeName)) {<!-- -->
                        name = xmlPullParser. nextText();
                    }
                    if ("version".equals(nodeName)) {<!-- -->
                        version = xmlPullParser. nextText();
                    }
                    break;
                case END_TAG:
                    if ("app".equals(nodeName)){<!-- -->
                        Log.d("YYYSS","id :" + id);
                        Log.d("YYYSS","name :" + name);
                        Log.d("YYYSS","version :" + version);
                    }
                    break;
            }
            //Get the next parsing event
            enventType = xmlPullParser. next();

        }

    } catch (XmlPullParserException e) {<!-- -->
        throw new RuntimeException(e);
    } catch (IOException e) {<!-- -->
        throw new RuntimeException(e);
    }
}

The data to be parsed is as follows:

image-20230731122123391

First construct a XmlPullParserFactory factory, and then build an XmlPullParser instance through this factory. Pass the data to be parsed into the instance.

You can get the current parsing event through **getEventType()**, and then continue parsing in a while loop, if the current parsing event is not equal to xmlPullParser.END_DOCUMENT(1), Indicates that the parsing work has not been completed, and the next parsing event can be obtained after calling the next() method.

In the while loop, We get the name of the current node through the getName() method, if the node name is found to be equal to id, name or version, call the **nextText()** method to get the specific The content of , and print out the obtained content every time an app node is parsed.

2. SAX analysis

2.1 Five methods of rewriting DefaultHandler

public class ContentHander extends DefaultHandler {<!-- -->
    private String nodeName;
    private StringBuilder id;
    private StringBuilder name;
    private StringBuilder version;

    //Called when starting to parse xml
    @Override
    public void startDocument() throws SAXException {<!-- -->
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    //Called when parsing xml is finished
    @Override
    public void endDocument() throws SAXException {<!-- -->
        super. endDocument();
    }

    //Called when starting to parse a node
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {<!-- -->
        //Record the current node name
        nodeName = localName;
    }

    //Called when parsing a node is complete
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {<!-- -->
        if ("id".equals(nodeName)) {<!-- -->
            Log.d("YYYSS", "id :" + id);
            Log.d("YYYSS", "name :" + name);
            Log.d("YYYSS", "version :" + version);
        }
        //clear ShringBuilder
        id. setLength(0);
        name. setLength(0);
        version.setLength(0);
    }

    //Called when getting the node content
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {<!-- -->
        // According to the current node name, determine which Stringbuilder object to add
        if ("id".equals(nodeName)) {<!-- -->
            id. append(ch, start, length);
        }else if ("name".equals(nodeName)) {<!-- -->
            name.append(ch, start, length);
        }else if ("version".equals(nodeName)) {<!-- -->
            version.append(ch, start, length);
        }
    }
}

2.2 SAX analysis steps

image-20230731152902875

private void parseXMlWithSAX(String xmlData) throws ParserConfigurationException, SAXException, IOException {<!-- -->
    // Create a SAX factory and get an XMLRead instance according to the factory
    SAXParserFactory factory = SAXParserFactory. newInstance();
    XMLReader reader = factory. newSAXParser(). getXMLReader();

    //Set the instance of ContenHander to XMLReader
    ContentHander hander = new ContentHander();
    reader.setContentHandler(hander);

    //Start parsing
    reader. parse(new InputSource(new StringReader(xmlData)));
}

InputSource is an input source class for SAX parser, which provides different types of data input sources, so that SAX parser can read and parse data from these sources.

4. Parse JSON format data

[
  {<!-- -->"id":"5","version":"5.5","name":"Clash of Clans"},
  {<!-- -->"id":"6","version":"7.0","name":"Boom Beach"},
  {<!-- -->"id":"7","version":"3.5","name":"clash royale"}
]

1. Use JSONObject

private void parseJSONWithJSONobject(String jsonData){<!-- -->
    try {<!-- -->
        //Get instance of JSONArray with data
        JSONArray jsonArray = new JSONArray(jsonData);

        //Start parsing
        for (int i = 0; i < jsonArray. length(); i ++ ) {<!-- -->
            JSONObject jsonObject = jsonArray. getJSONObject(i);
            Log.d("YHYHY",jsonObject.getString("id"));
            Log.d("YHYHY",jsonObject.getString("name"));
            Log.d("YHYHY",jsonObject.getString("version"));
        }

    } catch (JSONException e) {<!-- -->
        throw new RuntimeException(e);
    }
}

Since what we defined in the server is a JSON array, here is the number returned by the server first
It is rumored that people have arrived in a JS0NArray object.

Then loop through this JSONArray, and each element extracted from it is a JS0NObject object, and each JS0NObject object will contain data such as id, name and version .

Next, you only need to call the **getString()** method to retrieve these data.

2. Use GSON

github address: GSON

Add dependencies:

dependencies {<!-- -->
implementation 'com.google.code.gson:gson:2.10.1'
}

GSON is a very simple JSON data parsing method, which can map a piece of JSON data into an object.

The following code parses a JSON array:

private void parseJSONWithGSON(String jsonData){<!-- -->
    //Get GSON instance
    Gson gson = new Gson();
    
    // Map the List of GSON objects through GSON instances
    List<APP> appList = gson.fromJson(jsonData, new TypeToken<List<APP>>(){<!-- -->}.getType());

    for(APP app : appList){<!-- -->
        Log.d("SSXSXS","id:" + app.getId());
        Log.d("SSXSXS","name:" + app.getName());
        Log.d("SSXSXS","id:" + app.getVersion());
    }
}

If you are parsing a JSON data, you can use this method:

 APP app = gson.fromJson(jsonData, APP.class);

5. Network programming practice

Callback method using Okhttp:

public class HttpUtil {<!-- -->
    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {<!-- -->

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder().url(address).build();

        client.newCall(request).enqueue(callback);
    }
}

It can be seen that there is a okhttp3.Callback parameter in the send0kHttpRequest() method, which is a callback interface that comes with the OkHttp library.

Then after client, newCall() did not call the execute() method as before, but called an enqueue() method, and put okhttp.3.Callback Parameters are passed in.

OkHttp has helped us open a sub-thread inside the enqueue() method, and then execute the HTTP request in the sub-thread, and call back the final request result to Among okhttp3.Callback.

How to call the sengOkHttpRequest() method:

String address = "https://baidu.com";
HttpUtil.sendOkHttpRequest(address, new okhttp3.Callback() {<!-- -->
    @Override
    public void onFailure(Call call, IOException e) {<!-- -->
        //Handling of exceptions
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {<!-- -->
        //Get the response from the server
    }
});
syntaxbug.com © 2021 All Rights Reserved.