小应用 请求网络和解析数据

    xiaoxiao2021-12-14  21

    下面是一个小应用 身份证查询

    是这做成后的效果

    需求是这样的:

    首先写好xml布局 用的是线性布局 代码如下:

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.wmn.myceshi.MainActivity" android:weightSum="1"> <EditText android:hint="请输入身份证号码" android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/textView9" android:layout_marginTop="15dp" /> <Button android:text="身份查询" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:id="@+id/button3" /> <TextView android:layout_width="match_parent" android:layout_height="316dp" android:layout_marginTop="30dp" android:id="@+id/textView10" /> </LinearLayout>

    这里我只介绍一个 因为下面的2个和这第一个的写法是一样的 写好布局后 记得在清单文件中加入请求网络的权限: 然后是清单文件的配置 添加网络权限: <uses-permission android:name="android.permission.INTERNET"/> 写MainActicity的代码 : 首先找到 xml中的三个控件 通过 findViewById这个方法 设置 查询按钮的点击事件;setOnClickListene 当点击 查询按钮的 时候 请求网络 用的是okhttp 框架,把url 传进去,然后拼接好后面的参数 (key),(cardno)

    然后就会获取到一串字符 htmlStr= {“resultcode”:”200”,”reason”:”成功的返回”,”result”:{“area”:”xxx”,”sex”:”男”,”birthday”:”xxxx”,”verify”:”“},”error_code”:0}

    用android studio 下载GsonFormat 插件 创建一个javabean类,把 字符串自动导入 然后会自动生成一个javabean 用gson.fromJson 来解析, 把解析的数据 在TextView中显示出来,这里需要注意 记得添加runOnUiThread 线程,不然会报错 然后运行就可以查看了

    注意点: 请求网络okhttp, 数据的解析Gson

    转载请注明原文地址: https://ju.6miu.com/read-968123.html

    最新回复(0)