当前位置: 首页 > article >正文

Okhttp响应Json数据升级版源代码

一、网络访问

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">t.weather.itboy.net</domain>
    </domain-config>
</network-security-config>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:networkSecurityConfig="@xml/network"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

重点:

network:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">t.weather.itboy.net</domain>
    </domain-config>
</network-security-config>
<uses-permission android:name="android.permission.INTERNET"/>
android:networkSecurityConfig="@xml/network"

二、代码

public class MainActivity extends AppCompatActivity {
    TextView textView,textView2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              ReClient();
            }
        });
    }

    private void ReClient(){
        String url = "http://t.weather.itboy.net/api/weather/city/101260101";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                textView.setText(e.toString());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                ReSon(response);
            }
        });
    }

    private void ReSon(Response response){
        try (ResponseBody responseBody = response.body()){
            if (!response.isSuccessful()||responseBody==null){
                Log.e("22","错误"+response);
                return;
            }
            final String json = responseBody.string();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //textView.setText(json);
                    GsonJson(json);
                }
            });
        }catch (IOException e){
            Log.e("22","错误",e);
        }
    }

    private void GsonJson(String json){
        Gson gson = new Gson();
        try {
            MyJson myJson = gson.fromJson(json, MyJson.class);
            textView.setText(myJson.getDate());
            textView2.setText(myJson.cityInfo.getCity());
        }catch (Exception e){
            Log.e("JsonParsingError", "解析JSON数据时发生错误: " + e.getMessage());
        }
    }

    public class MyJson{
        private String date;
        private CityInfo cityInfo;
        private String getDate() {
            return date;
        }
        private CityInfo getCityInfo() {
            return cityInfo;
        }
        private class CityInfo{
            private String city;

            private String getCity() {
                return city;
            }
        }
    }
}
public class MainActivity extends AppCompatActivity {
    // 声明TextView控件,用于显示数据
    TextView textView, textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 调用自定义方法EdgeToEdge.enable来使界面铺满屏幕边缘到边缘(假设此方法存在并已实现)
        EdgeToEdge.enable(this);
        // 设置当前Activity的布局文件
        setContentView(R.layout.activity_main);

        // 通过findViewById查找XML布局文件中定义的Button
        Button button = findViewById(R.id.button);
        // 初始化TextView控件
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);

        // 为Button设置点击监听器,点击时触发网络请求
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 调用发送网络请求的方法
                ReClient();
            }
        });
    }

    // 发起网络请求的方法
    private void ReClient() {
        // 定义请求的URL,此处为贵阳市的天气API
        String url = "http://t.weather.itboy.net/api/weather/city/101260101";
        // 创建OkHttpClient实例,用于发送网络请求
        OkHttpClient client = new OkHttpClient();
        // 构建一个请求对象,设置URL
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 异步发送请求,当请求完成时,会在Callback中处理响应或失败情况
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 当请求失败时,更新textView显示错误信息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(e.toString());
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 请求成功时,调用ReSon方法处理响应数据
                ReSon(response);
            }
        });
    }

    // 处理网络响应的方法
    private void ReSon(Response response) {
        try (ResponseBody responseBody = response.body()) {
            // 检查响应是否成功且响应体不为空
            if (!response.isSuccessful() || responseBody == null) {
                // 记录错误日志
                Log.e("22", "错误" + response);
                return;
            }
            // 读取响应体中的字符串数据
            final String json = responseBody.string();
            // 在主线程中更新UI,避免UI操作在子线程进行
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 使用Gson解析JSON数据并更新UI
                    GsonJson(json);
                }
            });
        } catch (IOException e) {
            // 记录读取响应体时发生的错误
            Log.e("22", "错误", e);
        }
    }

    // 使用Gson解析JSON数据的方法
    private void GsonJson(String json) {
        // 创建Gson实例
        Gson gson = new Gson();
        try {
            // 将JSON字符串转换为MyJson对象
            MyJson myJson = gson.fromJson(json, MyJson.class);
            // 从MyJson对象中获取并设置日期到textView
            textView.setText(myJson.getDate());
            // 获取并设置城市信息到textView2
            textView2.setText(myJson.getCityInfo().getCity());
        } catch (Exception e) {
            // 记录解析JSON数据时发生的错误
            Log.e("JsonParsingError", "解析JSON数据时发生错误: " + e.getMessage());
        }
    }

    // 自定义数据类,用于映射JSON数据
    public class MyJson {
        private String date; // 日期字段
        private CityInfo cityInfo; // 城市信息对象

        // Getter方法,获取日期
        private String getDate() {
            return date;
        }

        // Getter方法,获取城市信息
        private CityInfo getCityInfo() {
            return cityInfo;
        }

        // 嵌套类,代表城市信息
        private class CityInfo {
            private String city; // 城市名称字段

            // Getter方法,获取城市名称
            private String getCity() {
                return city;
            }
        }
    }
}

 

 


http://www.kler.cn/a/597814.html

相关文章:

  • JS 算术运算符
  • 在 coc.nvim 插件中,自动补全时,候选词后面的 大写字母
  • 【机器学习】使用Python Spark MLlib进行预测模型训练
  • 【uniapp】内容瀑布流
  • 系统架构设计知识体系总结
  • k8s运维 设置Pod实现JVM内存根据容器内存动态调整
  • 使用BAT批处理加PYTHON进行WORD批量文字删除
  • 银河麒麟桌面版包管理器(五)
  • 使用vscode搭建pywebview集成vue项目示例
  • Android Coil3阶梯preload批量Bitmap拼接扁平宽图,Kotlin
  • Liunx系统Microsoft SQL Server数据库还原
  • 设计模式:创建型、结构型、行为型
  • 【Spring】深入理解 Spring 事务管理
  • Cesium 自定义路径导航材质
  • 运算放大器(一)运算放大器的参数、选型与应用
  • 防火墙设置屏蔽漏洞
  • 【leetcode题解】链表
  • mysql5.7及mysql8的一些特性
  • python包和模块
  • 深入理解指针(1)(C语言版)