Volley框架自帶的有圖片請(qǐng)求(ImageRequest),字符串請(qǐng)求(StringRequest),Json請(qǐng)求(JsonObjectRequest).我們開(kāi)篇介紹Volley的時(shí)候,已經(jīng)說(shuō)過(guò)Volley的代碼和設(shè)計(jì)短小精悍,易于定制.
下面我們以一個(gè)例子講解自定義請(qǐng)求Request.為了演示方便,我們自定義一個(gè)關(guān)于Json請(qǐng)求的Request
1,首先我們繼承Request類
然后實(shí)現(xiàn)parseNetworkResponse(NetworkResponse response)和deliverResponse(JSONObject response)方法.
parseNetworkResponse(NetworkResponse response)用于將獲取到的網(wǎng)絡(luò)結(jié)果轉(zhuǎn)換為需要的對(duì)象,例如JsonObject,Bitmap等.
deliverResponse(JSONObject response)主要用于將得到的結(jié)果回調(diào)到主線程
/**
* Created by zhaolei on 2017/2/15.
*/
public class MyJsonRequest extends Request<JSONObject> {
private Response.Listener mResponseListener ;
private static final String TAG = "request";
public MyJsonRequest(int method, String url,Response.Listener responseListenr, Response.ErrorListener listener) {
super(method, url, listener);
this.mResponseListener = responseListenr;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
Log.i(TAG,new String(response.data,"utf-8"));
Log.i(TAG,response.headers.toString());
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
if(mResponseListener != null){
mResponseListener.onResponse(response);
}
}
}
2,還是以請(qǐng)求天氣為例,獲取北京天氣數(shù)據(jù)
private void getWeatherData() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
MyJsonRequest request = new MyJsonRequest(Request.Method.GET,
"http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8",
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "onErrorResponse: "+error.toString());
}
});
requestQueue.add(request);
}
至此,自定義請(qǐng)求Request完畢,有沒(méi)有感覺(jué)Volley的設(shè)計(jì)很cool?