第一步:創建請求隊列
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
第二步:創建JSONObjectRequest請求,將請求添加到隊列中
url:上傳的認證信息;
utf8Url:將上傳的認證信息使用utf-8編碼;
mStrWeatherUrl :請求的地址;
private void transferByVolley(String url) throws JSONException {
Map<String, String> params = new HashMap<String, String>();
JSONObject jsonObject = new JSONObject(params);
String utf8Url = "";
try {
utf8Url = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.GET, mStrWeatherUrl + utf8Url, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//請求成功後返回的JSON數據,對其進行解析
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject dataobject = jsonObject.getJSONObject("XXX");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//添加請求失敗後的操作
}
}) {
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json;charset=UTF-8");
return headers;
}
};
//添加網絡請求
requestQueue.add(jsonRequest);
}
第三步:請求成功後取消隊列中的request
requestQueue.cancelAll(this);