【Android】使用网络技能——WebView的用法、http协议、OKHttp、解析XML、J ...

打印 上一主题 下一主题

主题 528|帖子 528|积分 1584

WebView的用法

新建一个WebView项目
修改activity_main中的代码:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:id="@+id/main"
  4.     android:orientation="vertical"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent">
  7.    
  8.     <WebView
  9.         android:id="@+id/web_view"
  10.         android:layout_width="match_parent"
  11.         android:layout_height="match_parent"/>
  12. </LinearLayout>
复制代码
我们在结构文件中用到了新的控件:WebView,用来表现网页
下来修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity {
  2.     @Override
  3.     protected void onCreate(Bundle savedInstanceState) {
  4.         super.onCreate(savedInstanceState);
  5.         setContentView(R.layout.activity_main);
  6.         WebView webView = (WebView) findViewById(R.id.web_view);
  7.         webView.getSettings().setJavaScriptEnabled(true);
  8.         webView.setWebChromeClient(new WebChromeClient());
  9.         webView.loadUrl("https://www.csdn.net/");
  10.         
  11.     }
  12. }
复制代码
末了到场网络申请权限就可以了:
  1.     <uses-permission android:name="android.permission.INTERNET"/>
复制代码
使用http协议:

新建NetworkTest项目
修改activity_main中的代码:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:id="@+id/main"
  4.     android:orientation="vertical"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent">
  7.     <Button
  8.         android:id="@+id/send_request"
  9.         android:layout_width="match_parent"
  10.         android:layout_height="wrap_content"
  11.         android:text="Send Request"/>
  12.    
  13.     <ScrollView
  14.         android:layout_width="match_parent"
  15.         android:layout_height="match_parent">
  16.         
  17.         <TextView
  18.             android:id="@+id/request_text"
  19.             android:layout_width="match_parent"
  20.             android:layout_height="wrap_content"/>
  21.     </ScrollView>
  22. </LinearLayout>
复制代码
修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     // 用于显示HTTP请求结果的TextView
  3.     TextView responseText;
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main);
  8.         // 获取发送请求按钮的引用
  9.         Button sendRequest = (Button) findViewById(R.id.send_request);
  10.         // 获取显示响应结果的TextView的引用
  11.         responseText = (TextView) findViewById(R.id.request_text);
  12.         // 为按钮设置点击监听器
  13.         sendRequest.setOnClickListener(this);
  14.     }
  15.     @Override
  16.     public void onClick(View v) {
  17.         // 检查点击事件是否来自发送请求按钮
  18.         if (v.getId() == R.id.send_request) {
  19.             // 发送HTTP请求
  20.             sendRequestWithHttpURLConnection();
  21.         }
  22.     }
  23.     // 使用HttpURLConnection发送HTTP请求
  24.     private void sendRequestWithHttpURLConnection() {
  25.         new Thread(new Runnable() {
  26.             @Override
  27.             public void run() {
  28.                 HttpURLConnection connection = null;
  29.                 BufferedReader reader = null;
  30.                 try {
  31.                     // 创建URL对象
  32.                     URL url = new URL("https://www.csdn.net/");
  33.                     // 打开HttpURLConnection
  34.                     connection = (HttpURLConnection) url.openConnection();
  35.                     // 设置请求方法为GET
  36.                     connection.setRequestMethod("GET");
  37.                     // 设置连接超时时间和读取超时时间
  38.                     connection.setConnectTimeout(8000);
  39.                     connection.setReadTimeout(8000);
  40.                     // 获取服务器响应的输入流
  41.                     InputStream in = connection.getInputStream();
  42.                     // 使用BufferedReader读取输入流
  43.                     reader = new BufferedReader(new InputStreamReader(in));
  44.                     StringBuilder response = new StringBuilder();
  45.                     String line;
  46.                     while ((line = reader.readLine()) != null) {
  47.                         response.append(line);
  48.                     }
  49.                     // 显示服务器响应
  50.                     showResponse(response.toString());
  51.                 } catch (Exception e) {
  52.                     e.printStackTrace();
  53.                 } finally {
  54.                     // 关闭BufferedReader
  55.                     if (reader != null) {
  56.                         try {
  57.                             reader.close();
  58.                         } catch (IOException e) {
  59.                             e.printStackTrace();
  60.                         }
  61.                     }
  62.                     // 断开HttpURLConnection连接
  63.                     if (connection != null) {
  64.                         connection.disconnect();
  65.                     }
  66.                 }
  67.             }
  68.         }).start();
  69.     }
  70.     // 在UI线程上显示服务器响应
  71.     private void showResponse(final String response) {
  72.         runOnUiThread(new Runnable() {
  73.             @Override
  74.             public void run() {
  75.                 responseText.setText(response);
  76.             }
  77.         });
  78.     }
  79. }
复制代码
末了还需要申请一下网络权限:
  1.     <uses-permission android:name="android.permission.INTERNET"/>
复制代码
假如想要提交数据给服务器可以举行如下修改:
  1. connection.setRequestMethod("POST");
  2. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  3. out.writeBytes("username=admin&password=123456");
复制代码
注意每条数据都要以键值对的情势存在,数据与数据之间用 & 分隔开
使用OKHttp

修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     // 用于显示网络请求响应的TextView
  3.     TextView responseText;
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main);
  8.         // 绑定按钮和TextView
  9.         Button sendRequest = (Button) findViewById(R.id.send_request);
  10.         responseText = (TextView) findViewById(R.id.request_text);
  11.         // 为按钮设置点击监听器
  12.         sendRequest.setOnClickListener(this);
  13.     }
  14.     @Override
  15.     public void onClick(View v) {
  16.         if (v.getId() == R.id.send_request) {
  17.             // 使用OkHttp发送网络请求
  18.             sendRequestWithOkHttp();
  19.         }
  20.     }
  21.     // 使用OkHttp发送网络请求的方法
  22.     private void sendRequestWithOkHttp() {
  23.         new Thread(new Runnable() {
  24.             @Override
  25.             public void run() {
  26.                 try {
  27.                     OkHttpClient client = new OkHttpClient();
  28.                     Request request = new Request.Builder()
  29.                             .url("https://www.csdn.net/")
  30.                             .build();
  31.                     Response response = client.newCall(request).execute();
  32.                     String responseData = response.body().string();
  33.                     showResponse(responseData);
  34.                 } catch (Exception e) {
  35.                     e.printStackTrace();
  36.                 }
  37.             }
  38.         }).start();
  39.     }
  40.     // 使用HttpURLConnection发送网络请求的方法
  41.     private void sendRequestWithHttpURLConnection() {
  42.         new Thread(new Runnable() {
  43.             @Override
  44.             public void run() {
  45.                 HttpURLConnection connection = null;
  46.                 BufferedReader reader = null;
  47.                 try {
  48.                     URL url = new URL("https://www.csdn.net/");
  49.                     connection = (HttpURLConnection) url.openConnection();
  50.                     connection.setRequestMethod("GET");
  51.                     connection.setConnectTimeout(8000);
  52.                     connection.setReadTimeout(8000);
  53.                     InputStream in = connection.getInputStream();
  54.                     reader = new BufferedReader(new InputStreamReader(in));
  55.                     StringBuilder response = new StringBuilder();
  56.                     String line;
  57.                     while ((line = reader.readLine()) != null) {
  58.                         response.append(line);
  59.                     }
  60.                     showResponse(response.toString());
  61.                 } catch (Exception e) {
  62.                     e.printStackTrace();
  63.                 } finally {
  64.                     // 关闭资源
  65.                     if (reader != null) {
  66.                         try {
  67.                             reader.close();
  68.                         } catch (IOException e) {
  69.                             e.printStackTrace();
  70.                         }
  71.                     }
  72.                     if (connection != null) {
  73.                         connection.disconnect();
  74.                     }
  75.                 }
  76.             }
  77.         }).start();
  78.     }
  79.     // 在UI线程中显示网络请求的响应数据
  80.     private void showResponse(final String response) {
  81.         runOnUiThread(new Runnable() {
  82.             @Override
  83.             public void run() {
  84.                 responseText.setText(response);
  85.             }
  86.         });
  87.     }
  88. }
复制代码
解析XML格式数据

先下载Apache服务器Welcome! - The Apache HTTP Server Project
下载安装后在根目录下的htdocs目录下,新建名为get_data.xml文件:
  1. <apps>
  2.         <app>
  3.                 <id>1</id>
  4.                 <name>Google Maps</name>
  5.                 <version>1.0</version>
  6.         </app>
  7.         <app>
  8.                 <id>2</id>
  9.                 <name>Chrome</name>
  10.                 <version>2.1</version>
  11.         </app>
  12.         <app>
  13.                 <id>3</id>
  14.                 <name>Google Play</name>
  15.                 <version>2.3</version>
  16.         </app>
  17. </apps>
复制代码
访问的内容为:

Pull解析

修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     TextView responseText;
  3.     @Override
  4.     protected void onCreate(Bundle savedInstanceState) {
  5.         super.onCreate(savedInstanceState);
  6.         setContentView(R.layout.activity_main);
  7.         Button sendRequest = (Button) findViewById(R.id.send_request);
  8.         responseText = (TextView) findViewById(R.id.request_text);
  9.         sendRequest.setOnClickListener(this);
  10.     }
  11.     @Override
  12.     public void onClick(View v) {
  13.         if (v.getId() == R.id.send_request) {
  14.             sendRequestWithOkHttp();
  15.         }
  16.     }
  17.     private void sendRequestWithOkHttp() {
  18.         new Thread(new Runnable() {
  19.             @Override
  20.             public void run() {
  21.                 try {
  22.                     OkHttpClient client = new OkHttpClient();
  23.                     Request request = new Request.Builder()
  24.                             .url("https://10.0.2.2/get_data.xml")
  25.                             .build();
  26.                     Response response = client.newCall(request).execute();
  27.                     String responseData = response.body().string();
  28.                     parseXmlWithPull(responseData);
  29.                 } catch (Exception e) {
  30.                     e.printStackTrace();
  31.                 }
  32.             }
  33.         }).start();
  34.     }
  35.     private void parseXmlWithPull(String xmlData) {
  36.         try {
  37.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  38.             XmlPullParser xmlPullParser = factory.newPullParser();
  39.             xmlPullParser.setInput(new StringReader(xmlData));
  40.             int eventType = xmlPullParser.getEventType();
  41.             String id = "";
  42.             String name = "";
  43.             String version = "";
  44.             while (eventType != XmlPullParser.END_DOCUMENT) {
  45.                 String nodeName = xmlPullParser.getName();
  46.                 switch (eventType) {
  47.                     case XmlPullParser.START_TAG:
  48.                         if ("id".equals(nodeName)) {
  49.                             id = xmlPullParser.nextText();
  50.                         } else if ("name".equals(nodeName)) {
  51.                             name = xmlPullParser.nextText();
  52.                         } else if ("version".equals(nodeName)) {
  53.                             version = xmlPullParser.nextText();
  54.                         }
  55.                         break;
  56.                     case XmlPullParser.END_TAG:
  57.                         if ("app".equals(nodeName)) {
  58.                             Log.d("MainActivity", "id is " + id);
  59.                             Log.d("MainActivity", "name is " + name);
  60.                             Log.d("MainActivity", "version is " + version);
  61.                         }
  62.                         break;
  63.                     default:
  64.                         break;
  65.                 }
  66.                 eventType = xmlPullParser.next();
  67.             }
  68.         } catch (Exception e) {
  69.             e.printStackTrace();
  70.         }
  71.     }
  72.     private void sendRequestWithHttpURLConnection() {
  73.         new Thread(new Runnable() {
  74.             @Override
  75.             public void run() {
  76.                 HttpURLConnection connection = null;
  77.                 BufferedReader reader = null;
  78.                 try {
  79.                     URL url = new URL("https://www.csdn.net/");
  80.                     connection = (HttpURLConnection) url.openConnection();
  81.                     connection.setRequestMethod("GET");
  82.                     connection.setConnectTimeout(8000);
  83.                     connection.setReadTimeout(8000);
  84.                     InputStream in = connection.getInputStream();
  85.                     reader = new BufferedReader(new InputStreamReader(in));
  86.                     StringBuilder response = new StringBuilder();
  87.                     String line;
  88.                     while ((line = reader.readLine()) != null) {
  89.                         response.append(line);
  90.                     }
  91.                     showResponse(response.toString());
  92.                 } catch (Exception e) {
  93.                     e.printStackTrace();
  94.                 } finally {
  95.                     if (reader != null) {
  96.                         try {
  97.                             reader.close();
  98.                         } catch (IOException e) {
  99.                             e.printStackTrace();
  100.                         }
  101.                     }
  102.                     if (connection != null) {
  103.                         connection.disconnect();
  104.                     }
  105.                 }
  106.             }
  107.         }).start();
  108.     }
  109.     private void showResponse(final String response) {
  110.         runOnUiThread(new Runnable() {
  111.             @Override
  112.             public void run() {
  113.                 responseText.setText(response);
  114.             }
  115.         });
  116.     }
  117. }
复制代码
但是开始运行后我们并没有乐成解析数据
本人碰到的题目是网络安全策略的限制被克制。默认情况下,从Android 9(API级别28)开始,应用程序不允许举行明文HTTP流量,以是需要修改应用的网络安全配置来允许明文流量。
创建网络安全配置文件:
在res/xml目录下创建一个名为network_security_config.xml的文件,并添加以下内容:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <network-security-config>
  3.     <domain-config cleartextTrafficPermitted="true">
  4.         <domain includeSubdomains="true">192.168.1.75</domain> <!-- 替换为您的局域网IP地址 -->
  5.     </domain-config>
  6. </network-security-config>
复制代码
引用网络安全配置文件
AndroidManifest.xml中引用这个网络安全配置文件:
  1. <application
  2.     android:networkSecurityConfig="@xml/network_security_config"
  3.     ...>
  4.     ...
  5. </application>
复制代码
修改MainActivity:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     private static final String TAG = "MainActivity";
  3.     TextView responseText;
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main);
  8.         Button sendRequest = findViewById(R.id.send_request);
  9.         responseText = findViewById(R.id.request_text);
  10.         sendRequest.setOnClickListener(this);
  11.     }
  12.     @Override
  13.     public void onClick(View v) {
  14.         if (v.getId() == R.id.send_request) {
  15.             sendRequestWithOkHttp();
  16.         }
  17.     }
  18.     private void sendRequestWithOkHttp() {
  19.         new Thread(new Runnable() {
  20.             @Override
  21.             public void run() {
  22.                 try {
  23.                     OkHttpClient client = new OkHttpClient();
  24.                     // 使用电脑的局域网IP地址
  25.                     Request request = new Request.Builder()
  26.                             .url("http://192.168.1.75/get_data.xml")
  27.                             .build();
  28.                     Response response = client.newCall(request).execute();
  29.                     String responseData = response.body().string();
  30.                     Log.d(TAG, "Response data: " + responseData);
  31.                     parseXmlWithPull(responseData);
  32.                 } catch (Exception e) {
  33.                     Log.e(TAG, "Request failed", e);
  34.                 }
  35.             }
  36.         }).start();
  37.     }
  38.     private void parseXmlWithPull(String xmlData) {
  39.         try {
  40.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  41.             XmlPullParser xmlPullParser = factory.newPullParser();
  42.             xmlPullParser.setInput(new StringReader(xmlData));
  43.             int eventType = xmlPullParser.getEventType();
  44.             String id = "";
  45.             String name = "";
  46.             String version = "";
  47.             while (eventType != XmlPullParser.END_DOCUMENT) {
  48.                 String nodeName = xmlPullParser.getName();
  49.                 switch (eventType) {
  50.                     case XmlPullParser.START_TAG:
  51.                         if ("id".equals(nodeName)) {
  52.                             id = xmlPullParser.nextText();
  53.                         } else if ("name".equals(nodeName)) {
  54.                             name = xmlPullParser.nextText();
  55.                         } else if ("version".equals(nodeName)) {
  56.                             version = xmlPullParser.nextText();
  57.                         }
  58.                         break;
  59.                     case XmlPullParser.END_TAG:
  60.                         if ("app".equals(nodeName)) {
  61.                             Log.i(TAG, "id is " + id);
  62.                             Log.i(TAG, "name is " + name);
  63.                             Log.i(TAG, "version is " + version);
  64.                         }
  65.                         break;
  66.                     default:
  67.                         break;
  68.                 }
  69.                 eventType = xmlPullParser.next();
  70.             }
  71.         } catch (Exception e) {
  72.             Log.e(TAG, "XML parsing failed", e);
  73.         }
  74.     }
  75.     private void sendRequestWithHttpURLConnection() {
  76.         new Thread(new Runnable() {
  77.             @Override
  78.             public void run() {
  79.                 HttpURLConnection connection = null;
  80.                 BufferedReader reader = null;
  81.                 try {
  82.                     URL url = new URL("http://192.168.1.75/get_data.xml");
  83.                     connection = (HttpURLConnection) url.openConnection();
  84.                     connection.setRequestMethod("GET");
  85.                     connection.setConnectTimeout(8000);
  86.                     connection.setReadTimeout(8000);
  87.                     InputStream in = connection.getInputStream();
  88.                     reader = new BufferedReader(new InputStreamReader(in));
  89.                     StringBuilder response = new StringBuilder();
  90.                     String line;
  91.                     while ((line = reader.readLine()) != null) {
  92.                         response.append(line);
  93.                     }
  94.                     showResponse(response.toString());
  95.                 } catch (Exception e) {
  96.                     Log.e(TAG, "Request failed", e);
  97.                 } finally {
  98.                     if (reader != null) {
  99.                         try {
  100.                             reader.close();
  101.                         } catch (IOException e) {
  102.                             e.printStackTrace();
  103.                         }
  104.                     }
  105.                     if (connection != null) {
  106.                         connection.disconnect();
  107.                     }
  108.                 }
  109.             }
  110.         }).start();
  111.     }
  112.     private void showResponse(final String response) {
  113.         runOnUiThread(new Runnable() {
  114.             @Override
  115.             public void run() {
  116.                 responseText.setText(response);
  117.             }
  118.         });
  119.     }
  120. }
复制代码
解析JSON格式数据

相比于XML,JSON的重要上风在于它的体积更小,在网络传输时可以更省流量
但是缺点在于它的语义性较差
起首在Apache目录下的htdocs目录中新建一个get_data.json文件,到场以下内容:
  1. [{"id":"5","version":"5.5","name":"Clash of Clans"},
  2. {"id":"6","version":"7.0","name":"Boom Beach"},
  3. {"id":"7","version":"3.5","name":"Clash Royale"}]
复制代码
在浏览器打开为:

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

修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     private static final String TAG = "MainActivity";
  3.     TextView responseText;
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main);
  8.         Button sendRequest = findViewById(R.id.send_request);
  9.         responseText = findViewById(R.id.request_text);
  10.         sendRequest.setOnClickListener(this);
  11.     }
  12.     @Override
  13.     public void onClick(View v) {
  14.         if (v.getId() == R.id.send_request) {
  15.             sendRequestWithOkHttp();
  16.         }
  17.     }
  18.     private void sendRequestWithOkHttp() {
  19.         new Thread(new Runnable() {
  20.             @Override
  21.             public void run() {
  22.                 try {
  23.                     OkHttpClient client = new OkHttpClient();
  24.                     Request request = new Request.Builder()
  25.                             .url("http://192.168.1.75/get_data.json") // 确认返回的是JSON数据
  26.                             .build();
  27.                     Response response = client.newCall(request).execute();
  28.                     String responseData = response.body().string();
  29.                     Log.d(TAG, "Response Data: " + responseData);
  30.                     parseJSONWithJSONObject(responseData);
  31.                 } catch (Exception e) {
  32.                     Log.e(TAG, "Request failed", e);
  33.                 }
  34.             }
  35.         }).start();
  36.     }
  37.     private void parseJSONWithJSONObject(String jsonData) {
  38.         try {
  39.             JSONArray jsonArray = new JSONArray(jsonData);
  40.             for (int i = 0; i < jsonArray.length(); i++) {
  41.                 JSONObject jsonObject = jsonArray.getJSONObject(i);
  42.                 String id = jsonObject.getString("id");
  43.                 String name = jsonObject.getString("name");
  44.                 String version = jsonObject.getString("version");
  45.                 Log.d(TAG, "id is " + id);
  46.                 Log.d(TAG, "name is " + name);
  47.                 Log.d(TAG, "version is " + version);
  48.             }
  49.         } catch (JSONException e) {
  50.             Log.e(TAG, "JSON parsing failed", e);
  51.         }
  52.     }
  53.     private void parseXmlWithPull(String xmlData) {
  54.         try {
  55.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  56.             XmlPullParser xmlPullParser = factory.newPullParser();
  57.             xmlPullParser.setInput(new StringReader(xmlData));
  58.             int eventType = xmlPullParser.getEventType();
  59.             String id = "";
  60.             String name = "";
  61.             String version = "";
  62.             while (eventType != XmlPullParser.END_DOCUMENT) {
  63.                 String nodeName = xmlPullParser.getName();
  64.                 switch (eventType) {
  65.                     case XmlPullParser.START_TAG:
  66.                         if ("id".equals(nodeName)) {
  67.                             id = xmlPullParser.nextText();
  68.                         } else if ("name".equals(nodeName)) {
  69.                             name = xmlPullParser.nextText();
  70.                         } else if ("version".equals(nodeName)) {
  71.                             version = xmlPullParser.nextText();
  72.                         }
  73.                         break;
  74.                     case XmlPullParser.END_TAG:
  75.                         if ("app".equals(nodeName)) {
  76.                             Log.i(TAG, "id is " + id);
  77.                             Log.i(TAG, "name is " + name);
  78.                             Log.i(TAG, "version is " + version);
  79.                         }
  80.                         break;
  81.                     default:
  82.                         break;
  83.                 }
  84.                 eventType = xmlPullParser.next();
  85.             }
  86.         } catch (Exception e) {
  87.             Log.e(TAG, "XML parsing failed", e);
  88.         }
  89.     }
  90.     private void sendRequestWithHttpURLConnection() {
  91.         new Thread(new Runnable() {
  92.             @Override
  93.             public void run() {
  94.                 HttpURLConnection connection = null;
  95.                 BufferedReader reader = null;
  96.                 try {
  97.                     URL url = new URL("http://192.168.1.75/get_data.json"); // 确认返回的是JSON数据
  98.                     connection = (HttpURLConnection) url.openConnection();
  99.                     connection.setRequestMethod("GET");
  100.                     connection.setConnectTimeout(8000);
  101.                     connection.setReadTimeout(8000);
  102.                     InputStream in = connection.getInputStream();
  103.                     reader = new BufferedReader(new InputStreamReader(in));
  104.                     StringBuilder response = new StringBuilder();
  105.                     String line;
  106.                     while ((line = reader.readLine()) != null) {
  107.                         response.append(line);
  108.                     }
  109.                     showResponse(response.toString());
  110.                 } catch (Exception e) {
  111.                     Log.e(TAG, "Request failed", e);
  112.                 } finally {
  113.                     if (reader != null) {
  114.                         try {
  115.                             reader.close();
  116.                         } catch (IOException e) {
  117.                             e.printStackTrace();
  118.                         }
  119.                     }
  120.                     if (connection != null) {
  121.                         connection.disconnect();
  122.                     }
  123.                 }
  124.             }
  125.         }).start();
  126.     }
  127.     private void showResponse(final String response) {
  128.         runOnUiThread(new Runnable() {
  129.             @Override
  130.             public void run() {
  131.                 responseText.setText(response);
  132.             }
  133.         });
  134.     }
  135. }
复制代码
使用GSON

要想使用GSON,起首需要添加依赖库:
  1. implementation("com.google.code.gson:gson:2.7")
复制代码
新建App类:
  1. package com.example.networktest;
  2. public class App {
  3.     private String id;
  4.     private String name;
  5.     private String version;
  6.    
  7.     public String getId() {
  8.         return id;
  9.     }
  10.     public void setId(String id) {
  11.         this.id = id;
  12.     }
  13.     public String getName() {
  14.         return name;
  15.     }
  16.     public void setName(String name) {
  17.         this.name = name;
  18.     }
  19.     public String getVersion() {
  20.         return version;
  21.     }
  22.     public void setVersion(String version) {
  23.         this.version = version;
  24.     }
  25.   
  26. }
复制代码
修改MainActivity中的代码:
  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2.     private static final String TAG = "MainActivity"; // 日志标签
  3.     TextView responseText; // 用于显示响应数据的TextView
  4.     @Override
  5.     protected void onCreate(Bundle savedInstanceState) {
  6.         super.onCreate(savedInstanceState);
  7.         setContentView(R.layout.activity_main); // 设置活动布局
  8.         Button sendRequest = findViewById(R.id.send_request); // 获取发送请求按钮
  9.         responseText = findViewById(R.id.request_text); // 获取用于显示响应的TextView
  10.         sendRequest.setOnClickListener(this); // 为按钮设置点击事件监听器
  11.     }
  12.     @Override
  13.     public void onClick(View v) {
  14.         if (v.getId() == R.id.send_request) { // 检查点击的视图ID是否为发送请求按钮
  15.             sendRequestWithOkHttp(); // 调用方法发送HTTP请求
  16.         }
  17.     }
  18.     // 使用OkHttp发送HTTP请求
  19.     private void sendRequestWithOkHttp() {
  20.         new Thread(new Runnable() {
  21.             @Override
  22.             public void run() {
  23.                 try {
  24.                     OkHttpClient client = new OkHttpClient();
  25.                     Request request = new Request.Builder()
  26.                             .url("http://192.168.1.75/get_data.json") // 请求URL
  27.                             .build();
  28.                     Response response = client.newCall(request).execute(); // 执行请求
  29.                     String responseData = response.body().string(); // 获取响应数据
  30.                     parseJSONWithGSON(responseData); // 解析JSON数据
  31.                 } catch (Exception e) {
  32.                     Log.e(TAG, "Request failed", e); // 记录请求失败的日志
  33.                 }
  34.             }
  35.         }).start();
  36.     }
  37.     // 使用GSON解析JSON数据
  38.     private void parseJSONWithGSON(String jsonData) {
  39.         Gson gson = new Gson();
  40.         List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType()); // 将JSON数据转换为App对象列表
  41.         for (App app : appList) {
  42.             Log.d("MainActivity", "id is " + app.getId());
  43.             Log.d("MainActivity", "name is " + app.getName());
  44.             Log.d("MainActivity", "version is " + app.getVersion());
  45.         }
  46.     }
  47.     // 使用JSONObject解析JSON数据
  48.     private void parseJSONWithJSONObject(String jsonData) {
  49.         try {
  50.             JSONArray jsonArray = new JSONArray(jsonData); // 创建JSON数组
  51.             for (int i = 0; i < jsonArray.length(); i++) {
  52.                 JSONObject jsonObject = jsonArray.getJSONObject(i);
  53.                 String id = jsonObject.getString("id");
  54.                 String name = jsonObject.getString("name");
  55.                 String version = jsonObject.getString("version");
  56.                 Log.d(TAG, "id is " + id);
  57.                 Log.d(TAG, "name is " + name);
  58.                 Log.d(TAG, "version is " + version);
  59.             }
  60.         } catch (JSONException e) {
  61.             Log.e(TAG, "JSON parsing failed", e); // 记录JSON解析失败的日志
  62.         }
  63.     }
  64.     // 使用Pull解析XML数据
  65.     private void parseXmlWithPull(String xmlData) {
  66.         try {
  67.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  68.             XmlPullParser xmlPullParser = factory.newPullParser();
  69.             xmlPullParser.setInput(new StringReader(xmlData));
  70.             int eventType = xmlPullParser.getEventType();
  71.             String id = "";
  72.             String name = "";
  73.             String version = "";
  74.             while (eventType != XmlPullParser.END_DOCUMENT) {
  75.                 String nodeName = xmlPullParser.getName();
  76.                 switch (eventType) {
  77.                     case XmlPullParser.START_TAG:
  78.                         if ("id".equals(nodeName)) {
  79.                             id = xmlPullParser.nextText();
  80.                         } else if ("name".equals(nodeName)) {
  81.                             name = xmlPullParser.nextText();
  82.                         } else if ("version".equals(nodeName)) {
  83.                             version = xmlPullParser.nextText();
  84.                         }
  85.                         break;
  86.                     case XmlPullParser.END_TAG:
  87.                         if ("app".equals(nodeName)) {
  88.                             Log.i(TAG, "id is " + id);
  89.                             Log.i(TAG, "name is " + name);
  90.                             Log.i(TAG, "version is " + version);
  91.                         }
  92.                         break;
  93.                     default:
  94.                         break;
  95.                 }
  96.                 eventType = xmlPullParser.next();
  97.             }
  98.         } catch (Exception e) {
  99.             Log.e(TAG, "XML parsing failed", e); // 记录XML解析失败的日志
  100.         }
  101.     }
  102.     // 使用HttpURLConnection发送HTTP请求
  103.     private void sendRequestWithHttpURLConnection() {
  104.         new Thread(new Runnable() {
  105.             @Override
  106.             public void run() {
  107.                 HttpURLConnection connection = null;
  108.                 BufferedReader reader = null;
  109.                 try {
  110.                     URL url = new URL("http://192.168.1.75/get_data.json"); // 请求URL
  111.                     connection = (HttpURLConnection) url.openConnection();
  112.                     connection.setRequestMethod("GET");
  113.                     connection.setConnectTimeout(8000);
  114.                     connection.setReadTimeout(8000);
  115.                     InputStream in = connection.getInputStream();
  116.                     reader = new BufferedReader(new InputStreamReader(in));
  117.                     StringBuilder response = new StringBuilder();
  118.                     String line;
  119.                     while ((line = reader.readLine()) != null) {
  120.                         response.append(line);
  121.                     }
  122.                     showResponse(response.toString()); // 显示响应数据
  123.                 } catch (Exception e) {
  124.                     Log.e(TAG, "Request failed", e); // 记录请求失败的日志
  125.                 } finally {
  126.                     if (reader != null) {
  127.                         try {
  128.                             reader.close();
  129.                         } catch (IOException e) {
  130.                             e.printStackTrace();
  131.                         }
  132.                     }
  133.                     if (connection != null) {
  134.                         connection.disconnect();
  135.                     }
  136.                 }
  137.             }
  138.         }).start();
  139.     }
  140.     // 在主线程上显示响应数据
  141.     private void showResponse(final String response) {
  142.         runOnUiThread(new Runnable() {
  143.             @Override
  144.             public void run() {
  145.                 responseText.setText(response);
  146.             }
  147.         });
  148.     }
  149. }
复制代码
打印结果如图所示:


已经到底啦!!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

用户国营

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表