【Android移动开发】使用okhttputils+gson解析解析json数据查询手机号码归属地区号等

首先申请key值,天行、聚合等都行,我用的是聚合数据免费的查询号码归属地api,到聚合数据注册进行实名认证后可以获取到key值,这个很重要,没有请求不了数据。
在这里插入图片描述
在这里插入图片描述

实现效果:
在这里插入图片描述

分析

首先测试一下接口,看看它返回的json数据:
在这里插入图片描述
接口地址:

http://apis.juhe.cn/mobile/get

请求参数中phone为必填,魔人返回json格式

返回的数据内容:

{
    
    
	"resultcode":"200",
	"reason":"Return Successd!",
	"result":{
    
    
		"province":"广东",
		"city":"广州",
		"areacode":"020",
		"zip":"510000",
		"company":"电信",
		"card":""
	},
	"error_code":0
}

返回的数据内容中为resultcode、reason、result、error_code。其中result又嵌套province、city、areacode、zip、company、card

根据号码模拟测试我们可以获取如下信息:

 * 手机号码段	180xxxxxx
 * 卡号归属地	省份 城市
 * 运营商	xx
 * 区号	xxx
 * 邮编	xxxxxx

添加依赖

在这里插入图片描述
在项目的app目录下的build.gradle里面添加如下:

implementation 'com.zhy:okhttputils:2.6.2'
implementation("com.squareup.okhttp3:okhttp:4.9.0")
implementation 'com.google.code.gson:gson:2.7'

然后再同步构建一下。

PhoneBean.class

从上面我们提取有用的值,并写相应的Bean类:PhoneBean.class

package com.lyx.mycommunity.bean;
/**
 * @author create by liyingxia
 * 创建日期:2020/12/23 22:32
 * 包名: com.example.sqlite.OKhttp
 */

/**
 * {
 *         "resultcode":"200",
 *         "reason":"Return Successd!",
 *         "result":{
 *         "province":"广东",
 *         "city":"广州",
 *         "areacode":"020",
 *         "zip":"510000",
 *         "company":"联通",
 *         "card":""
 *         },
 *         "error_code":0
 *         }
 */

public class JsonBean {
    
    
    public String resultcode;
    public String reason;
    public Result result;

    public static class Result {
    
    
        public String province;
        public String city;
        public String areacode;
        public String zip;
        public String company;
        public String card;

        public String getProvince() {
    
    
            return province;
        }

        public void setProvince(String province) {
    
    
            this.province = province;
        }

        public String getCity() {
    
    
            return city;
        }

        public void setCity(String city) {
    
    
            this.city = city;
        }

        public String getAreacode() {
    
    
            return areacode;
        }

        public void setAreacode(String areacode) {
    
    
            this.areacode = areacode;
        }

        public String getZip() {
    
    
            return zip;
        }

        public void setZip(String zip) {
    
    
            this.zip = zip;
        }

        public String getCompany() {
    
    
            return company;
        }

        public void setCompany(String company) {
    
    
            this.company = company;
        }

        public String getCard() {
    
    
            return card;
        }

        public void setCard(String card) {
    
    
            this.card = card;
        }
    }


    @Override
    public String toString() {
    
    
        return "JsonBean{" +
                "reason='" + reason + '\'' +
                ", resultcode='" + resultcode + '\'' +
                ", result=" + result +
                '}';
    }
}

MainActivity:

(也可以写在Activity里面,这里我写在Fragment里面,所以取名为ServiceFragment,差不多)

package com.lyx.mycommunity.fragment;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyx.mycommunity.base.BaseFragment;
import com.lyx.mycommunity.bean.JsonBean;
import com.lyx.shoppingcity.R;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author create by liyingxia
 * 创建日期:2020/12/23 23:10:45
 * 描述:
 */
public class ServiceFragment extends BaseFragment {
    
    
    private static final String TAG = ServiceFragment.class.getSimpleName();
    private TextView tv_msg;
    private EditText edt_phone;
    private Button btn_query;
    private OkHttpClient client;

    @Override
    public View initView() {
    
    
        Log.e(TAG," 服务的视图被实例化了");
        View view = View.inflate(myContext, R.layout.fragment_service,null);
        findview(view);
        initListener();
        return view;
    }

    private void findview(View view) {
    
    
        edt_phone=(EditText)view.findViewById(R.id.edt_phone);
        tv_msg=(TextView)view.findViewById(R.id.tv_msg);
        btn_query=(Button)view.findViewById(R.id.btn_query);

    }

    private void initListener() {
    
    
        btn_query.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                new Thread() {
    
    
                    @Override
                    public void run() {
    
    
                        try{
    
    
                            new GetGuiShuDi().run();}
                        catch (Exception e){
    
    
                            Log.i("aaaa","Exception"+e.getCause()+e.getMessage());
                        }
                    }
                }.start();
            }
        });
    }

    @Override
    public void initData() {
    
    
        super.initData();
        Log.e(TAG," 分类数据被初始化了");
       // textView.setText(" 分类");
        client=new OkHttpClient();
    }
  
    public class GetGuiShuDi{
    
    
        String string = edt_phone.getText().toString();
        private void run() {
    
    
            Request request = new Request.Builder()
                    .url("http://apis.juhe.cn/mobile/get?phone="+string+"&key="+"这里写你申请的key值")  // ”key“+=“你的key值”
                    .get()
                    .build();
            try{
    
    
                Response response = client.newCall(request).execute();
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<JsonBean>() {
    
    }.getType();
                final JsonBean jsonBean = gson.fromJson(response.body().string(), type);
                getActivity().runOnUiThread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        tv_msg.setText("查询号码:"+string+"\n"+"号码归属地:"+jsonBean.result.province+" "+jsonBean.result.city+"\n"+"运营商:"+jsonBean.result.company+"\n"+"归属地:" + jsonBean.result.city+"\n"
                                +"区号:"+jsonBean.result.areacode+"\n"+"邮编:"+jsonBean.result.zip);
                    }
                });
                Log.i("json+++++++++++++", jsonBean.result.city);
            }catch (Exception e){
    
    
                Log.i("json++++++++++++", e.getMessage()+"/"+e.getCause());
            }
        }
    }
}

布局文件:fragment_service.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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:background="@mipmap/bgbg"
    android:orientation="vertical">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageButton
        android:id="@+id/service_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/top_bar_left_back"
        android:background="@null"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微记服务"
        android:textColor="#733096"
        android:textStyle="bold"
        android:textSize="24sp"
        android:layout_marginBottom="30dp"
        android:gravity="center"/>
</RelativeLayout>
    <EditText
        android:id="@+id/edt_phone"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:paddingLeft="20dp"
        android:layout_marginBottom="30dp"
        android:background="@mipmap/btnbgfff"
        android:hint="请输入查询号码"
       />
    <Button
        android:layout_width="match_parent"
        android:layout_height="40sp"
        android:text="查询归属地"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"
        android:background="@mipmap/btnbg"
        android:id="@+id/btn_query"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询信息:"
        android:layout_marginLeft="10dp"
        android:textColor="#848484"/>
    <TextView
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_msg"/>

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/weixin_43853746/article/details/111600948