2025.5.26

学习内容:
1.网络权限配置:在AndroidManifest.xml文件中添加网络访问权限:

HttpURLConnection 使用:使用 HttpURLConnection 发送 HTTP 请求,获取网络数据。以下是一个发送 GET 请求的示例:
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            final String responseData = stringBuilder.toString();

            // 在UI线程更新UI
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 处理响应数据
                    textView.setText(responseData);
                }
            });
        }
        connection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}).start();
JSON 数据解析:学习使用原生 API 解析 JSON 数据。假设服务器返回的 JSON 数据格式为:
{
"name": "张三",
"age": 25,
"hobbies": ["阅读", "旅行", "编程"]
}
解析代码如下:
try {
JSONObject jsonObject = new JSONObject(jsonData);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONArray hobbiesArray = jsonObject.getJSONArray("hobbies");
List hobbies = new ArrayList<>();
for (int i = 0; i < hobbiesArray.length(); i++) {
hobbies.add(hobbiesArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
收获
了解了 Android 网络编程的基本流程,学会使用 HttpURLConnection 发送 HTTP 请求并处理响应数据,掌握了 JSON 数据的解析方法。由于网络操作不能在主线程进行,学会了使用子线程处理网络请求,然后在 UI 线程更新界面,解决了网络操作与 UI 更新的线程同步问题。

posted @ 2025-05-26 23:03  被迫敲代码  阅读(9)  评论(0)    收藏  举报