【Android】使用网络技术——WebView的用法、http协议、OKHttp、解析XML、JSON格式数据笔记整理

news2025/2/23 4:14:09

WebView的用法

新建一个WebView项目

修改activity_main中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

我们在布局文件中用到了新的控件:WebView,用来显示网页

下来修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl("https://www.csdn.net/");
        
    }
}

最后加入网络申请权限就可以了:

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

使用http协议:

新建NetworkTest项目

修改activity_main中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>
    
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <TextView
            android:id="@+id/request_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>
</LinearLayout>

修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 用于显示HTTP请求结果的TextView
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取发送请求按钮的引用
        Button sendRequest = (Button) findViewById(R.id.send_request);

        // 获取显示响应结果的TextView的引用
        responseText = (TextView) findViewById(R.id.request_text);

        // 为按钮设置点击监听器
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 检查点击事件是否来自发送请求按钮
        if (v.getId() == R.id.send_request) {
            // 发送HTTP请求
            sendRequestWithHttpURLConnection();
        }
    }

    // 使用HttpURLConnection发送HTTP请求
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    // 创建URL对象
                    URL url = new URL("https://www.csdn.net/");

                    // 打开HttpURLConnection
                    connection = (HttpURLConnection) url.openConnection();

                    // 设置请求方法为GET
                    connection.setRequestMethod("GET");

                    // 设置连接超时时间和读取超时时间
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    // 获取服务器响应的输入流
                    InputStream in = connection.getInputStream();

                    // 使用BufferedReader读取输入流
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    // 显示服务器响应
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭BufferedReader
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    // 断开HttpURLConnection连接
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // 在UI线程上显示服务器响应
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

最后还需要申请一下网络权限:

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

如果想要提交数据给服务器可以进行如下修改:

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

注意每条数据都要以键值对的形式存在,数据与数据之间用 & 分隔开

使用OKHttp

修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 用于显示网络请求响应的TextView
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 绑定按钮和TextView
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.request_text);

        // 为按钮设置点击监听器
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            // 使用OkHttp发送网络请求
            sendRequestWithOkHttp();
        }
    }

    // 使用OkHttp发送网络请求的方法
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.csdn.net/")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // 使用HttpURLConnection发送网络请求的方法
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.csdn.net/");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭资源
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // 在UI线程中显示网络请求的响应数据
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

解析XML格式数据

先下载Apache服务器Welcome! - The Apache HTTP Server Project

下载安装后在根目录下的htdocs目录下,新建名为get_data.xml文件:

<apps>
	<app>
		<id>1</id>
		<name>Google Maps</name>
		<version>1.0</version>
	</app>
	<app>
		<id>2</id>
		<name>Chrome</name>
		<version>2.1</version>
	</app>
	<app>
		<id>3</id>
		<name>Google Play</name>
		<version>2.3</version>
	</app>
</apps>

访问的内容为:

image-20240806160908355

Pull解析

修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.request_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://10.0.2.2/get_data.xml")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseXmlWithPull(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseXmlWithPull(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.d("MainActivity", "id is " + id);
                            Log.d("MainActivity", "name is " + name);
                            Log.d("MainActivity", "version is " + version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.csdn.net/");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

但是开始运行后我们并没有成功解析数据

本人遇到的问题是网络安全策略的限制被禁止。默认情况下,从Android 9(API级别28)开始,应用程序不允许进行明文HTTP流量,所以需要修改应用的网络安全配置来允许明文流量。

创建网络安全配置文件:

res/xml目录下创建一个名为network_security_config.xml的文件,并添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.75</domain> <!-- 替换为您的局域网IP地址 -->
    </domain-config>
</network-security-config>

引用网络安全配置文件

AndroidManifest.xml中引用这个网络安全配置文件:

<application
    android:networkSecurityConfig="@xml/network_security_config"
    ...>
    ...
</application>

修改MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.request_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    // 使用电脑的局域网IP地址
                    Request request = new Request.Builder()
                            .url("http://192.168.1.75/get_data.xml") 
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "Response data: " + responseData);
                    parseXmlWithPull(responseData);
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e);
                }
            }
        }).start();
    }

    private void parseXmlWithPull(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.i(TAG, "id is " + id);
                            Log.i(TAG, "name is " + name);
                            Log.i(TAG, "version is " + version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            Log.e(TAG, "XML parsing failed", e);
        }
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://192.168.1.75/get_data.xml"); 
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

解析JSON格式数据

相比于XML,JSON的主要优势在于它的体积更小,在网络传输时可以更省流量

但是缺点在于它的语义性较差

首先在Apache目录下的htdocs目录中新建一个get_data.json文件,加入以下内容:

[{"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"}]

在浏览器打开为:

image-20240806201033387

下面就可以开始解析数据了:

使用JSONObject

修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.request_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.1.75/get_data.json") // 确认返回的是JSON数据
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d(TAG, "Response Data: " + responseData);
                    parseJSONWithJSONObject(responseData);
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e);
                }
            }
        }).start();
    }

    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d(TAG, "id is " + id);
                Log.d(TAG, "name is " + name);
                Log.d(TAG, "version is " + version);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON parsing failed", e);
        }
    }

    private void parseXmlWithPull(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.i(TAG, "id is " + id);
                            Log.i(TAG, "name is " + name);
                            Log.i(TAG, "version is " + version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            Log.e(TAG, "XML parsing failed", e);
        }
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://192.168.1.75/get_data.json"); // 确认返回的是JSON数据
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

使用GSON

要想使用GSON,首先需要添加依赖库:

implementation("com.google.code.gson:gson:2.7")

新建App类:

package com.example.networktest;

public class App {

    private String id;
    private String name;
    private String version;
    
    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

  
}

修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity"; // 日志标签
    TextView responseText; // 用于显示响应数据的TextView

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 设置活动布局
        Button sendRequest = findViewById(R.id.send_request); // 获取发送请求按钮
        responseText = findViewById(R.id.request_text); // 获取用于显示响应的TextView
        sendRequest.setOnClickListener(this); // 为按钮设置点击事件监听器
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) { // 检查点击的视图ID是否为发送请求按钮
            sendRequestWithOkHttp(); // 调用方法发送HTTP请求
        }
    }

    // 使用OkHttp发送HTTP请求
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.1.75/get_data.json") // 请求URL
                            .build();
                    Response response = client.newCall(request).execute(); // 执行请求
                    String responseData = response.body().string(); // 获取响应数据
                    parseJSONWithGSON(responseData); // 解析JSON数据
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e); // 记录请求失败的日志
                }
            }
        }).start();
    }

    // 使用GSON解析JSON数据
    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType()); // 将JSON数据转换为App对象列表
        for (App app : appList) {
            Log.d("MainActivity", "id is " + app.getId());
            Log.d("MainActivity", "name is " + app.getName());
            Log.d("MainActivity", "version is " + app.getVersion());
        }
    }

    // 使用JSONObject解析JSON数据
    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData); // 创建JSON数组
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d(TAG, "id is " + id);
                Log.d(TAG, "name is " + name);
                Log.d(TAG, "version is " + version);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON parsing failed", e); // 记录JSON解析失败的日志
        }
    }

    // 使用Pull解析XML数据
    private void parseXmlWithPull(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)) {
                            Log.i(TAG, "id is " + id);
                            Log.i(TAG, "name is " + name);
                            Log.i(TAG, "version is " + version);
                        }
                        break;
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            Log.e(TAG, "XML parsing failed", e); // 记录XML解析失败的日志
        }
    }

    // 使用HttpURLConnection发送HTTP请求
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://192.168.1.75/get_data.json"); // 请求URL
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString()); // 显示响应数据
                } catch (Exception e) {
                    Log.e(TAG, "Request failed", e); // 记录请求失败的日志
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // 在主线程上显示响应数据
    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
}

打印结果如图所示:

image-20240807100732949


已经到底啦!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1990346.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

STM32F1之SysTick系统定时器详细解析

目录 1. 简介 2. SysTick功能框图 3. SysTick寄存器 3.1 SysTick控制及状态寄存器 3.2 SysTick重装载数值寄存器 3.3 SysTick当前数值寄存器 3.4 SysTick校准数值寄存器 4. SysTick定时时间计算 5. SysTick寄存器结构体 6. 写一个us级延时函数 7. 写一个…

240806-RHEL 无法通过 ssh username@ip 远程连接,报错:Connection closed by ip port 22

A. 原因排查 遇到这个错误通常意味着 SSH 服务可能在目标主机上没有正常运行&#xff0c;或有防火墙/网络配置问题。以下是一些排查步骤&#xff1a; 检查 SSH 服务状态&#xff1a; 确认 SSH 服务是否正在目标主机上运行。 sudo systemctl status sshd重启 SSH 服务&#xff…

探索 Python 异步通信的奥秘:WebSockets 库的神奇之旅

文章目录 探索 Python 异步通信的奥秘&#xff1a;WebSockets 库的神奇之旅背景&#xff1a;为何选择 WebSockets&#xff1f;什么是 websockets 库&#xff1f;安装 websockets 库5个简单的库函数使用方法场景应用示例常见问题与解决方案总结 探索 Python 异步通信的奥秘&…

用Manim实现三维坐标系的绘制

1.ThreeDAxes 函数 ThreeDAxes是 Manim 中用于创建三维坐标系的类。在manim中常用的三位坐标绘制函数是&#xff1a; class ThreeDAxes(x_range(-6, 6, 1), y_range(-5, 5, 1), z_range(-4, 4, 1), x_length10.5, y_length10.5, z_length6.5, z_axis_configNone, z_normala…

数据仓库怎么建设?一文详解数仓的建设过程!

随着信息技术的飞速发展&#xff0c;企业不仅需要存储和管理海量数据&#xff0c;更迫切需要从这些数据中提取有价值的信息&#xff0c;以支持复杂的决策制定过程。数据仓库不仅是存储数据的场所&#xff0c;更是支持复杂查询、报告和数据分析的强有力工具&#xff0c;其建设已…

JavaScript异步简介|Promise快速入门

异步&#xff08;Asynchronous, async&#xff09;是与同步&#xff08;Synchronous, sync&#xff09;相对的概念。 异步 JavaScript 简介 异步编程技术使你的程序可以在执行一个可能长期运行的任务的同时继续对其他事件做出反应而不必等待任务完成。与此同时&#xff0c;你…

Linux工具|运维工具rename常用命令详解

&#x1f4eb; 作者简介&#xff1a;「六月暴雪飞梨花」&#xff0c;专注于研究Java&#xff0c;就职于科技型公司后端工程师 &#x1f3c6; 近期荣誉&#xff1a;华为云云享专家、阿里云专家博主、腾讯云优秀创作者、ACDU成员 &#x1f525; 三连支持&#xff1a;欢迎 ❤️关注…

【vulnhub】Wakanda :1靶机

靶机安装 下载地址&#xff1a;https://download.vulnhub.com/wakanda/wakanda-1.ova 运行环境&#xff1a;Virtual Box 信息收集 靶机IP扫描 netdiscover -i eth0 -r 192.168.7.0/24 端口扫描 nmap -A 192.168.7.243 -p- 80端口开启了http服务&#xff0c;在3333端口开启…

案例研究丨盛泰光电携手DataEase实现数据驱动智能制造

盛泰光电科技股份有限公司&#xff08;以下简称为“盛泰光电”&#xff09;是中国第一批摄像头模组制造企业。自成立至今&#xff0c;一直专注于手机摄像头模组的研发、制造、销售与服务&#xff0c;并向非手机包括笔记本、车载、医疗、AIoT等领域延伸&#xff0c;形成以手机摄…

PHP + Laravel + RabbitMQ + Redis 实现消息队列 (二) 消费队列在RabbitMQ和redis中的简单使用

最简单的队列功能 RabbitMQ和消息传递通常会使用一些术语&#xff1a; 生产者&#xff08;Producer&#xff09;意味着发送消息。一个发送消息的程序称为生产者。队列&#xff08;Queue&#xff09;尽管消息通过RabbitMQ和您的应用程序流动&#xff0c;但它们只能存储在队列中…

数据结构(01):数据结构概述(基本术语、逻辑结构和物理结构)

1、数据结构概述 (1)基本术语 A.数据元素 具有一定意义的基本单位。如人类的数据元素是人&#xff08;张三、李四等&#xff09;。 B.数据项 可以看作是数据元素的属性。如人的属性&#xff08;姓名、年龄、身高等&#xff09; C.数据对象 性质相同的数据元素的集合。如某一栋…

群聊的创建 表情包发送 图片发送

目录 群聊&#xff1a; ​编辑 表情包发送&#xff1a; 图片发送&#xff1a; 群聊&#xff1a; 1.群资料的表groupinformation 字段&#xff1a;GroupId 群id&#xff0c;GroupName 群名&#xff0c;CreatTime 创群时间&#xff0c;CreatUserId 创群的人&#xff0c;…

萤石云 ezuikit-js创建的播放器实例esc取消全屏后变黑屏

原因&#xff1a;上层页面重新设置了容器的宽高&#xff0c;导致uikit退出全屏时宽高计算异常 解决方法&#xff1a;实例初始化的时候会传入宽高width、height&#xff0c;播放器的画面尺寸是根据这两个参数设置的&#xff0c;然后退出全屏会回到这两个值

计算机的错误计算(五十五)

摘要 展示大数的余弦函数值的错误计算。 根据国际IEEE 754 标准[1]&#xff0c;包括余弦在内的三角函数的定义域是整个实数范围&#xff1a; 但是&#xff0c;实际情况怎样呢&#xff1f; 例1. 计算 . 在 Python下计算&#xff1a; x30**65 print(x) import math print(ma…

只强的Java学习之路8-7

一. 安装配置nodejs npm create vitelatest npm install vue-router npm install axios npm install element-plus --save npm run dev https://element-plus.org/zh-CN/#/zh-CN 新建项目&#xff1a; easy.vue <script setup></script><!--绑定数据-->…

在vue中页面使用了动态组件组件导致首次页面加载时子组件样式不显示,刷新后才正常

问题&#xff1a; 在vue中页面使用了动态组件组件导致首次页面加载时子组件样式不显示&#xff0c;刷新后才正常。 原因&#xff1a; 因为动态组件的延迟加载&#xff0c;如果使用了Vue的动态组件&#xff08;如<component :is"...">&#xff09;&#xff0c;…

【代码随想录】有序数组的平方

本博文为《代码随想录》的学习笔记&#xff0c;原文链接&#xff1a;代码随想录 题目 977. 有序数组的平方 给你一个按 非递减顺序 排序的整数数组 nums&#xff0c;返回 每个数字的平方 组成的新数组&#xff0c;要求也按 非递减顺序 排序。 示例 1&#xff1a; 输入&…

6种常用的AR跟踪方法

增强现实 (AR) 是一项令人着迷的技术&#xff0c;可将虚拟内容与现实世界无缝集成。实现这种无缝集成的关键组件之一是跟踪。各种类型的跟踪用于确定 AR 内容在环境中的准确位置和方向。本文介绍 AR 最常见的6种跟踪方法。 NSDT工具推荐&#xff1a; Three.js AI纹理开发包 - Y…

ctfshow-web入门-sql注入(web191-web195)

目录 1、web191 2、web192 3、web193 4、web194 5、web195 1、web191 过滤了 ascii 使用 ord 代替&#xff1a; import requests import string url "http://a585c278-320a-40e7-841f-109b1e394caa.challenge.ctf.show/api/index.php" out for j in range(1…

哈佛大学单细胞课程|笔记汇总 (五)

哈佛大学单细胞课程|笔记汇总 &#xff08;四&#xff09; &#xff08;五&#xff09;Count Normalization and Principal Component Analysis 获得高质量的单细胞后&#xff0c;单细胞RNA-seq&#xff08;scRNA-seq&#xff09;分析工作流程的下一步就是执行聚类。聚类的目…