利用Volley框架实现手机号归属地查询

接口地址:https://www.juhe.cn/docs/api/id/11

首先必须声明权限:

<uses-permission android:name="android.permission.INTERNET"/>

添加jar包并在application中注册:

public class MyApplication extends Application {
    public static RequestQueue queue;
    @Override
    public void onCreate() {
        super.onCreate();
        queue = Volley.newRequestQueue(getApplicationContext());
    }
    public static RequestQueue getHttpQueue() {
        return queue;
    }
}

Get方法获取数据:       

    private void volleyGet() {
        final String URL_GET = url + "phone=" + phoneNum + "&key=" + APIKEY;
        StringRequest request = new StringRequest(Method.GET, URL_GET, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response);
                tvGet.setText(praseResponse(response));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_LONG).show();
            } 
        });
        request.setTag(GET_TAG);
        MyApplication.getHttpQueue().add(request);
    }

Post方法获取数据:

  private void volleyPost() {
        StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response);
                tvPost.setText(praseResponse(response));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_LONG).show();
            } 
        }){
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("phone", phoneNum);
                map.put("key", APIKEY);
                return map;
            }
        };
        request.setTag(POST_TAG);
        MyApplication.getHttpQueue().add(request);
    }

解析获取到的JSON数据:

    //将JSON数据格式化显示
    private String praseResponse(String response){
        StringBuffer result = new StringBuffer();    
        int begin = response.indexOf('{', 1);
        //防止获取不到数据时程序崩溃
        if(begin < 0){
            Toast.makeText(MainActivity.this, "数据不规范", Toast.LENGTH_LONG).show();
            return "";
        }    
        String str = response.substring(begin);
        result.append("省份: "+praseJSON(str, "province")+"
");
        result.append("城市: "+praseJSON(str, "city")+"
");
        result.append("区号: "+praseJSON(str, "areacode")+"
");
        result.append("邮编: "+praseJSON(str, "zip")+"
");
        result.append("运营商: "+praseJSON(str, "company")+"
");
        result.append("卡类型: "+praseJSON(str, "card")+"
");
        return result.toString();
    }
    private String praseJSON(String str, String str1) {
        try {
            JSONObject jb = new JSONObject(str);
            System.out.println(str);
            System.out.println(str1);
            return jb.getString(str1);
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("wsm");
            return null;
        }
    }

最后不要忘记在程序结束时处理:

    @Override
    protected void onStop() {
        MyApplication.getHttpQueue().cancelAll(POST_TAG);
        MyApplication.getHttpQueue().cancelAll(GET_TAG);
        super.onStop();
    }

实现效果(分别为GET和POST方法获取):

原文地址:https://www.cnblogs.com/mycd/p/5703747.html