标签:
首先必须声明权限:
<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; } }
API接口:https://www.juhe.cn/docs/api/id/11
Get:
rivate void volley_Get() { 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) { 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 volley_Post() { StringRequest request = new StringRequest(Method.POST, url, new Listener<String>() { @Override public void onResponse(String 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); }
praseResponse:
//将JSON数据格式化显示 private String praseResponse(String response){ StringBuffer result = new StringBuffer(); int begin = response.indexOf(‘{‘, 1); String str = response.substring(begin); result.append("省份: "+praseJSON(str, "province")+"\n"); result.append("城市: "+praseJSON(str, "city")+"\n"); result.append("区号: "+praseJSON(str, "areacode")+"\n"); result.append("邮编: "+praseJSON(str, "zip")+"\n"); result.append("运营商: "+praseJSON(str, "company")+"\n"); result.append("卡类型: "+praseJSON(str, "card")+"\n"); 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; } }
标签:
原文地址:http://www.cnblogs.com/mycd/p/5703747.html