Volley它很是適合去進行數據量不大,但通訊頻繁的網絡操做,而對於大數據量的網絡操做,好比說下載文件等,Volley的表現就會很是糟糕。 因此不建議用它去進行下載文件、加載大圖的操做。有人可能會問,若是我服務器中的圖片都挺大的,activity中listview要加載這些圖片,是不 是不能用這個框架呢?其實這個問題自己就是錯誤的,你想若是你服務器的圖片都是大圖,你要在手機上用照片牆進行展現,下載圖片都會慢的要死,這個自己就是 不可行的。因此在項目初期就應該創建好服務器端的小圖,照片牆用加載小圖,點擊後再從網絡上下載大圖,這纔是正確思路。這時你就能夠用volley加載小 圖了,若是是要加載大圖,能夠用別的算法,強烈建議手動完成大圖清除的工做,不然極可能會出現OOM。Volley自己沒有作什麼回收算法,仍是用最基本 的GC,實際使用中能夠根據須要自定義一下。html
零、準備工做java
Git項目,添加爲lib,申請權限android
git clone https://android.googlesource.com/platform/frameworks/volley
<uses-permission android:name="android.permission.INTERNET" />
1、初始化請求對象——RequestQueuegit
public class MyApplication extends Application { public static RequestQueue requestQueue; @Override public void onCreate() { super.onCreate(); // 沒必要爲每一次HTTP請求都建立一個RequestQueue對象,推薦在application中初始化 requestQueue = Volley.newRequestQueue(this); } }
既然是Http操做,天然有請求和響應,RequestQueue是一個請求隊列 對象,它能夠緩存全部的HTTP請求,而後按照必定的算法併發地發出這些請求。RequestQueue內部的設計就是很是合適高併發的,所以咱們沒必要爲 每一次HTTP請求都建立一個RequestQueue對象,這是很是浪費資源的。因此在這裏我創建了一個application,而後用單例模式定義了 這個對象。固然,你能夠選擇在一個activity中定義一個RequestQueue對象,但這樣可能會比較麻煩,並且還可能出現請求隊列包含 activity強引用的問題,所以我仍是推薦在application中定義。算法
2、使用StringRequest接收String類型的響應express
前 面定義了請求對象,那麼天然就有接收響應的對象了,這個框架中有多個響應對象,像StringRequest接受到的響應就是string類型 的;JsonRequest接收的響應就是Json類型對象。其實它們都是繼承自Request<T>,而後根據不一樣的響應數據來進行特殊的 處理。apache
2.1 初始化json
/** * Creates a new request with the given method. * * @param method the request {@link Method} to use * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener)
/** * Creates a new GET request. * * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) { this(Method.GET, url, listener, errorListener); }
這就是StringRequest的兩個構造函數,不一樣之處是一個傳入了一個method的參數,一個沒有。其實看上面的源碼就知道,若是你不傳入method,默認會調用GET方式進行請求。當你傳入了Method.POST就會用post來請求。數組
【參數解釋】緩存
url:請求的地址
listener:響應成功的監聽器
errorListener:出錯時的監聽器
StringRequest getStringRequest = new StringRequest("http://www.baidu.com", new ResponseListener(), new ResponseErrorListener());
StringRequest postStringRequest = new StringRequest(Method.POST, "http://www.baidu.com", new ResponseListener(),null);
2.2 配置監聽器
/** * @author:Jack Tony * @description :設置響應結果監聽器,由於用的是StringRequest,因此這裏的結果我定義爲string類型 * @date :2015年1月24日 */ private class ResponseListener implements Response.Listener<String>{ @Override public void onResponse(String response) { // TODO 自動生成的方法存根 Log.d("TAG", "-------------\n" + response); } } /** * @author:Jack Tony * @description :訪問出錯時觸發的監聽器 * @date :2015年1月28日 */ private class ResponseErrorListener implements Response.ErrorListener{ @Override public void onErrorResponse(VolleyError error) { // TODO 自動生成的方法存根 Log.e("TAG", error.getMessage(), error); } }
這兩個監聽器沒啥可說的,由於是StringRequest調用的,因此成功時觸發的監聽器中獲得的response就是String類型。若是訪問出錯,那麼就打印出錯信息。
2.3 執行GET請求
如今咱們有了請求對象和響應對象,外加處理響應結果的監聽器,那麼就執行最後一步——發送請求。發送請求很簡單,將響應對象添加到請求隊列便可。
mQueue.add(getStringRequest);
完整代碼:
RequestQueue mQueue = MyApplication.requestQueue;
StringRequest getStringRequest = new StringRequest("http://www.baidu.com", new ResponseListener(), new ResponseErrorListener()); mQueue.add(getStringRequest);
經過簡單的add()方法就直接發送了請求,若是服務器響應了請求就會觸發咱們的結果監聽器,而後被打印出啦。如今請求的是百度,因此獲得了網頁的源碼:
2.4 執行POST請求
POST和GET同樣,僅僅是傳入的方法不一樣。但通常咱們的post都是要帶一些參數的,volley沒有提供附加參數的方法,因此咱們必需要在StringRequest的匿名類中重寫getParams()方法:
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("params1", "value1"); map.put("params2", "value2"); return map; } };
這 樣就傳入了value1和value2兩個參數了。如今可能有人會問爲啥這個框架不提供這個傳參的方法,還非得讓咱們重寫。我我的以爲這個框架自己的目的 就是執行頻繁的網絡請求,好比下載圖片,解析json數據什麼的,用GET就能很好的實現了,因此就沒有提供傳參的POST方法。爲了簡單起見,我重寫了 Request類中的getParams(),添加了傳參的方法,之後經過setParams()就能夠傳參數了。
重寫的代碼塊:
Map<String, String> mParams = null; /** * Returns a Map of parameters to be used for a POST or PUT request. Can throw * {@link AuthFailureError} as authentication may be required to provide these values. * * <p>Note that you can directly override {@link #getBody()} for custom data.</p> * * @throws AuthFailureError in the event of auth failure */ protected Map<String, String> getParams() throws AuthFailureError { return mParams; } public void setParams(Map<String, String> params){ mParams = params; }
完整代碼:
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Collections; import java.util.Map; import android.net.TrafficStats; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.text.TextUtils; import com.android.volley.VolleyLog.MarkerLog; /** * Base class for all network requests. * * @param <T> The type of parsed response this request expects. */ public abstract class Request<T> implements Comparable<Request<T>> { /** * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}. */ private static final String DEFAULT_PARAMS_ENCODING = "UTF-8"; /** * Supported request methods. */ public interface Method { int DEPRECATED_GET_OR_POST = -1; int GET = 0; int POST = 1; int PUT = 2; int DELETE = 3; int HEAD = 4; int OPTIONS = 5; int TRACE = 6; int PATCH = 7; } /** An event log tracing the lifetime of this request; for debugging. */ private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null; /** * Request method of this request. Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS, * TRACE, and PATCH. */ private final int mMethod; /** URL of this request. */ private final String mUrl; /** Default tag for {@link TrafficStats}. */ private final int mDefaultTrafficStatsTag; /** Listener interface for errors. */ private final Response.ErrorListener mErrorListener; /** Sequence number of this request, used to enforce FIFO ordering. */ private Integer mSequence; /** The request queue this request is associated with. */ private RequestQueue mRequestQueue; /** Whether or not responses to this request should be cached. */ private boolean mShouldCache = true; /** Whether or not this request has been canceled. */ private boolean mCanceled = false; /** Whether or not a response has been delivered for this request yet. */ private boolean mResponseDelivered = false; // A cheap variant of request tracing used to dump slow requests. private long mRequestBirthTime = 0; /** Threshold at which we should log the request (even when debug logging is not enabled). */ private static final long SLOW_REQUEST_THRESHOLD_MS = 3000; /** The retry policy for this request. */ private RetryPolicy mRetryPolicy; /** * When a request can be retrieved from cache but must be refreshed from * the network, the cache entry will be stored here so that in the event of * a "Not Modified" response, we can be sure it hasn't been evicted from cache. */ private Cache.Entry mCacheEntry = null; /** An opaque token tagging this request; used for bulk cancellation. */ private Object mTag; /** * Creates a new request with the given URL and error listener. Note that * the normal response listener is not provided here as delivery of responses * is provided by subclasses, who have a better idea of how to deliver an * already-parsed response. * * @deprecated Use {@link #Request(int, String, com.android.volley.Response.ErrorListener)}. */ @Deprecated public Request(String url, Response.ErrorListener listener) { this(Method.DEPRECATED_GET_OR_POST, url, listener); } /** * Creates a new request with the given method (one of the values from {@link Method}), * URL, and error listener. Note that the normal response listener is not provided here as * delivery of responses is provided by subclasses, who have a better idea of how to deliver * an already-parsed response. */ public Request(int method, String url, Response.ErrorListener listener) { mMethod = method; mUrl = url; mErrorListener = listener; setRetryPolicy(new DefaultRetryPolicy()); mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url); } /** * Return the method for this request. Can be one of the values in {@link Method}. */ public int getMethod() { return mMethod; } /** * Set a tag on this request. Can be used to cancel all requests with this * tag by {@link RequestQueue#cancelAll(Object)}. * * @return This Request object to allow for chaining. */ public Request<?> setTag(Object tag) { mTag = tag; return this; } /** * Returns this request's tag. * @see Request#setTag(Object) */ public Object getTag() { return mTag; } /** * @return this request's {@link com.android.volley.Response.ErrorListener}. */ public Response.ErrorListener getErrorListener() { return mErrorListener; } /** * @return A tag for use with {@link TrafficStats#setThreadStatsTag(int)} */ public int getTrafficStatsTag() { return mDefaultTrafficStatsTag; } /** * @return The hashcode of the URL's host component, or 0 if there is none. */ private static int findDefaultTrafficStatsTag(String url) { if (!TextUtils.isEmpty(url)) { Uri uri = Uri.parse(url); if (uri != null) { String host = uri.getHost(); if (host != null) { return host.hashCode(); } } } return 0; } /** * Sets the retry policy for this request. * * @return This Request object to allow for chaining. */ public Request<?> setRetryPolicy(RetryPolicy retryPolicy) { mRetryPolicy = retryPolicy; return this; } /** * Adds an event to this request's event log; for debugging. */ public void addMarker(String tag) { if (MarkerLog.ENABLED) { mEventLog.add(tag, Thread.currentThread().getId()); } else if (mRequestBirthTime == 0) { mRequestBirthTime = SystemClock.elapsedRealtime(); } } /** * Notifies the request queue that this request has finished (successfully or with error). * * <p>Also dumps all events from this request's event log; for debugging.</p> */ void finish(final String tag) { if (mRequestQueue != null) { mRequestQueue.finish(this); } if (MarkerLog.ENABLED) { final long threadId = Thread.currentThread().getId(); if (Looper.myLooper() != Looper.getMainLooper()) { // If we finish marking off of the main thread, we need to // actually do it on the main thread to ensure correct ordering. Handler mainThread = new Handler(Looper.getMainLooper()); mainThread.post(new Runnable() { @Override public void run() { mEventLog.add(tag, threadId); mEventLog.finish(this.toString()); } }); return; } mEventLog.add(tag, threadId); mEventLog.finish(this.toString()); } else { long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime; if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) { VolleyLog.d("%d ms: %s", requestTime, this.toString()); } } } /** * Associates this request with the given queue. The request queue will be notified when this * request has finished. * * @return This Request object to allow for chaining. */ public Request<?> setRequestQueue(RequestQueue requestQueue) { mRequestQueue = requestQueue; return this; } /** * Sets the sequence number of this request. Used by {@link RequestQueue}. * * @return This Request object to allow for chaining. */ public final Request<?> setSequence(int sequence) { mSequence = sequence; return this; } /** * Returns the sequence number of this request. */ public final int getSequence() { if (mSequence == null) { throw new IllegalStateException("getSequence called before setSequence"); } return mSequence; } /** * Returns the URL of this request. */ public String getUrl() { return mUrl; } /** * Returns the cache key for this request. By default, this is the URL. */ public String getCacheKey() { return getUrl(); } /** * Annotates this request with an entry retrieved for it from cache. * Used for cache coherency support. * * @return This Request object to allow for chaining. */ public Request<?> setCacheEntry(Cache.Entry entry) { mCacheEntry = entry; return this; } /** * Returns the annotated cache entry, or null if there isn't one. */ public Cache.Entry getCacheEntry() { return mCacheEntry; } /** * Mark this request as canceled. No callback will be delivered. */ public void cancel() { mCanceled = true; } /** * Returns true if this request has been canceled. */ public boolean isCanceled() { return mCanceled; } /** * Returns a list of extra HTTP headers to go along with this request. Can * throw {@link AuthFailureError} as authentication may be required to * provide these values. * @throws AuthFailureError In the event of auth failure */ public Map<String, String> getHeaders() throws AuthFailureError { return Collections.emptyMap(); } /** * Returns a Map of POST parameters to be used for this request, or null if * a simple GET should be used. Can throw {@link AuthFailureError} as * authentication may be required to provide these values. * * <p>Note that only one of getPostParams() and getPostBody() can return a non-null * value.</p> * @throws AuthFailureError In the event of auth failure * * @deprecated Use {@link #getParams()} instead. */ @Deprecated protected Map<String, String> getPostParams() throws AuthFailureError { return getParams(); } /** * Returns which encoding should be used when converting POST parameters returned by * {@link #getPostParams()} into a raw POST body. * * <p>This controls both encodings: * <ol> * <li>The string encoding used when converting parameter names and values into bytes prior * to URL encoding them.</li> * <li>The string encoding used when converting the URL encoded parameters into a raw * byte array.</li> * </ol> * * @deprecated Use {@link #getParamsEncoding()} instead. */ @Deprecated protected String getPostParamsEncoding() { return getParamsEncoding(); } /** * @deprecated Use {@link #getBodyContentType()} instead. */ @Deprecated public String getPostBodyContentType() { return getBodyContentType(); } /** * Returns the raw POST body to be sent. * * @throws AuthFailureError In the event of auth failure * * @deprecated Use {@link #getBody()} instead. */ @Deprecated public byte[] getPostBody() throws AuthFailureError { // Note: For compatibility with legacy clients of volley, this implementation must remain // here instead of simply calling the getBody() function because this function must // call getPostParams() and getPostParamsEncoding() since legacy clients would have // overridden these two member functions for POST requests. Map<String, String> postParams = getPostParams(); if (postParams != null && postParams.size() > 0) { return encodeParameters(postParams, getPostParamsEncoding()); } return null; } Map<String, String> mParams = null; /** * Returns a Map of parameters to be used for a POST or PUT request. Can throw * {@link AuthFailureError} as authentication may be required to provide these values. * * <p>Note that you can directly override {@link #getBody()} for custom data.</p> * * @throws AuthFailureError in the event of auth failure */ protected Map<String, String> getParams() throws AuthFailureError { return mParams; } public void setParams(Map<String, String> params){ mParams = params; } /** * Returns which encoding should be used when converting POST or PUT parameters returned by * {@link #getParams()} into a raw POST or PUT body. * * <p>This controls both encodings: * <ol> * <li>The string encoding used when converting parameter names and values into bytes prior * to URL encoding them.</li> * <li>The string encoding used when converting the URL encoded parameters into a raw * byte array.</li> * </ol> */ protected String getParamsEncoding() { return DEFAULT_PARAMS_ENCODING; } /** * Returns the content type of the POST or PUT body. */ public String getBodyContentType() { return "application/x-www-form-urlencoded; charset=" + getParamsEncoding(); } /** * Returns the raw POST or PUT body to be sent. * * <p>By default, the body consists of the request parameters in * application/x-www-form-urlencoded format. When overriding this method, consider overriding * {@link #getBodyContentType()} as well to match the new body format. * * @throws AuthFailureError in the event of auth failure */ public byte[] getBody() throws AuthFailureError { Map<String, String> params = getParams(); if (params != null && params.size() > 0) { return encodeParameters(params, getParamsEncoding()); } return null; } /** * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string. */ private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) { StringBuilder encodedParams = new StringBuilder(); try { for (Map.Entry<String, String> entry : params.entrySet()) { encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding)); encodedParams.append('='); encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding)); encodedParams.append('&'); } return encodedParams.toString().getBytes(paramsEncoding); } catch (UnsupportedEncodingException uee) { throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee); } } /** * Set whether or not responses to this request should be cached. * * @return This Request object to allow for chaining. */ public final Request<?> setShouldCache(boolean shouldCache) { mShouldCache = shouldCache; return this; } /** * Returns true if responses to this request should be cached. */ public final boolean shouldCache() { return mShouldCache; } /** * Priority values. Requests will be processed from higher priorities to * lower priorities, in FIFO order. */ public enum Priority { LOW, NORMAL, HIGH, IMMEDIATE } /** * Returns the {@link Priority} of this request; {@link Priority#NORMAL} by default. */ public Priority getPriority() { return Priority.NORMAL; } /** * Returns the socket timeout in milliseconds per retry attempt. (This value can be changed * per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry * attempts remaining, this will cause delivery of a {@link TimeoutError} error. */ public final int getTimeoutMs() { return mRetryPolicy.getCurrentTimeout(); } /** * Returns the retry policy that should be used for this request. */ public RetryPolicy getRetryPolicy() { return mRetryPolicy; } /** * Mark this request as having a response delivered on it. This can be used * later in the request's lifetime for suppressing identical responses. */ public void markDelivered() { mResponseDelivered = true; } /** * Returns true if this request has had a response delivered for it. */ public boolean hasHadResponseDelivered() { return mResponseDelivered; } /** * Subclasses must implement this to parse the raw network response * and return an appropriate response type. This method will be * called from a worker thread. The response will not be delivered * if you return null. * @param response Response from the network * @return The parsed response, or null in the case of an error */ abstract protected Response<T> parseNetworkResponse(NetworkResponse response); /** * Subclasses can override this method to parse 'networkError' and return a more specific error. * * <p>The default implementation just returns the passed 'networkError'.</p> * * @param volleyError the error retrieved from the network * @return an NetworkError augmented with additional information */ protected VolleyError parseNetworkError(VolleyError volleyError) { return volleyError; } /** * Subclasses must implement this to perform delivery of the parsed * response to their listeners. The given response is guaranteed to * be non-null; responses that fail to parse are not delivered. * @param response The parsed response returned by * {@link #parseNetworkResponse(NetworkResponse)} */ abstract protected void deliverResponse(T response); /** * Delivers error message to the ErrorListener that the Request was * initialized with. * * @param error Error details */ public void deliverError(VolleyError error) { if (mErrorListener != null) { mErrorListener.onErrorResponse(error); } } /** * Our comparator sorts from high to low priority, and secondarily by * sequence number to provide FIFO ordering. */ @Override public int compareTo(Request<T> other) { Priority left = this.getPriority(); Priority right = other.getPriority(); // High-priority requests are "lesser" so they are sorted to the front. // Equal priorities are sorted by sequence number to provide FIFO ordering. return left == right ? this.mSequence - other.mSequence : right.ordinal() - left.ordinal(); } @Override public String toString() { String trafficStatsTag = "0x" + Integer.toHexString(getTrafficStatsTag()); return (mCanceled ? "[X] " : "[ ] ") + getUrl() + " " + trafficStatsTag + " " + getPriority() + " " + mSequence; } }
使用示例:
StringRequest postStringRequest = new StringRequest(Method.POST, "http://m.weather.com.cn/data/101010100.html", new ResponseListener(), null); Map<String, String> map = new HashMap<String, String>(); map.put("params1", "value1"); map.put("params2", "value2"); postStringRequest.setParams(map); mQueue.add(postStringRequest);
結果:
3、使用JsonObjectRequest接收Json類型的響應
相似於StringRequest,JsonRequest也是繼承自Request類的,不過因爲JsonRequest是一個抽象類,所以咱們沒法直接建立它的實例,那麼只能從它的子類入手了。JsonRequest有兩個直接的子類,JsonObjectRequest和JsonArrayRequest,從名字上你應該能就看出它們的區別了吧?一個是用於請求一段JSON數據的,一個是用於請求一段JSON數組的。
3.1 構造函數
/** * Creates a new request. * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) { super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); } /** * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is * <code>null</code>, <code>POST</code> otherwise. * * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener) */ public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) { this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, errorListener); }
3.2 發送請求
和以前講過的StringRequest同樣,能夠傳入請求的類型,若是沒傳就默認是GET請求。參數也是一模一樣,就是泛型變了下。定義和使用的方式也徹底一致,初始化對象後,添加到請求隊列便可。
JsonObjectRequest request = new JsonObjectRequest("http://m.weather.com.cn/data/101010100.html", null, new ResponseListener(), new ResponseErrorListener()); mQueue.add(request);
/** * @author:Jack Tony * @description :設置響應結果監聽器,這裏用的是JsonObjectRequest,因此返回的結果是JSONObject * @date :2015年1月24日 */ private class ResponseListener implements Response.Listener<JSONObject> { @Override public void onResponse(JSONObject response) { // TODO 自動生成的方法存根 Log.d("TAG", "-------------\n" + response.toString()); } } /** * @author:Jack Tony * @description :訪問出錯時觸發的監聽器 * @date :2015年1月28日 */ private class ResponseErrorListener implements Response.ErrorListener { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); } }
結果:
你怎麼查看解析是否成功了呢?服務器端的數據:
{"weatherinfo":{"city":"北京","city_en":"beijing","date_y":"2014年3月4日","date":"","week":"星期二","fchh":"11","cityid":"101010100","temp1":"8℃~-3℃","temp2":"8℃~-3℃","temp3":"7℃~-3℃","temp4":"8℃~-1℃","temp5":"10℃~1℃","temp6":"10℃~2℃","tempF1":"46.4℉~26.6℉","tempF2":"46.4℉~26.6℉","tempF3":"44.6℉~26.6℉","tempF4":"46.4℉~30.2℉","tempF5":"50℉~33.8℉","tempF6":"50℉~35.6℉","weather1":"晴","weather2":"晴","weather3":"晴","weather4":"晴轉多雲","weather5":"多雲","weather6":"多雲","img1":"0","img2":"99","img3":"0","img4":"99","img5":"0","img6":"99","img7":"0","img8":"1","img9":"1","img10":"99","img11":"1","img12":"99","img_single":"0","img_title1":"晴","img_title2":"晴","img_title3":"晴","img_title4":"晴","img_title5":"晴","img_title6":"晴","img_title7":"晴","img_title8":"多雲","img_title9":"多雲","img_title10":"多雲","img_title11":"多雲","img_title12":"多雲","img_title_single":"晴","wind1":"北風4-5級轉微風","wind2":"微風","wind3":"微風","wind4":"微風","wind5":"微風","wind6":"微風","fx1":"北風","fx2":"微風","fl1":"4-5級轉小於3級","fl2":"小於3級","fl3":"小於3級","fl4":"小於3級","fl5":"小於3級","fl6":"小於3級","index":"寒冷","index_d":"天氣寒冷,建議着厚羽絨服、毛皮大衣加厚毛衣等隆冬服裝。年老體弱者尤爲要注意保暖防凍。","index48":"冷","index48_d":"天氣冷,建議着棉服、羽絨服、皮夾克加羊毛衫等冬季服裝。年老體弱者宜着厚棉衣、冬大衣或厚羽絨服。","index_uv":"中等","index48_uv":"中等","index_xc":"較適宜","index_tr":"通常","index_co":"較溫馨","st1":"7","st2":"-3","st3":"8","st4":"0","st5":"7","st6":"-1","index_cl":"較不宜","index_ls":"基本適宜","index_ag":"易發"}}
若是解析錯誤,就會出現警告,這時錯誤監聽器就會被觸發:
若是解析成功,就不會出現錯誤,這就是泛型的好處,保證了程序的正確性。
最終咱們就能夠在Response.Listener<JSONObject>中獲得JSONObject對象,經過這個對象就能進行下一步的處理了。
3.3 解析Json
好比要解析出上面Json數據中city的字段,就能夠按照以下方式編碼:
try { response = response.getJSONObject("weatherinfo"); Log.i(TAG, "City = " + response.getString("city")); } catch (JSONException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }
完整監聽器代碼:
private class ResponseListener implements Response.Listener<JSONObject> { @Override public void onResponse(JSONObject response) { // TODO 自動生成的方法存根 Log.d("TAG", "-------------\n" + response.toString()); try { response = response.getJSONObject("weatherinfo"); Log.i(TAG, "City = " + response.getString("city")); } catch (JSONException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } }
結果:
4、JsonArrayRequest簡介
除此以外,還有一個相關的響應對象叫作JsonArrayRequest,這個得到的就是一個Json序列,使用方式沒有任何改變,這裏就不作過多介紹了,由於剩下的就是Json的知識了,和Volley沒有任何關係。
源碼:
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley.toolbox; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import org.json.JSONArray; import org.json.JSONException; import java.io.UnsupportedEncodingException; /** * A request for retrieving a {@link JSONArray} response body at a given URL. */ public class JsonArrayRequest extends JsonRequest<JSONArray> { /** * Creates a new request. * @param url URL to fetch the JSON from * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) { super(Method.GET, url, null, listener, errorListener); } @Override protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) { try { String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(new JSONArray(jsonString), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JSONException je) { return Response.error(new ParseError(je)); } } }
經過源碼咱們知道,這個響應對象發送的請求是Get,並且它是繼承自JsonRequest,若是你想用POST來作,自行添加新的構造函數便可。
4、請求取消
@Override public void onStop() { for (Request <?> req : mRequestQueue) { req.cancel(); } }
@Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); mRequestQueue.cancelAll(this); }
給請求設置標籤:
若是你想取消全部的請求,在onStop方法中添加以下代碼:
@Override protected void onStop() { super.onStop(); mRequestQueue.cancelAll(new RequestQueue.RequestFilter() { @Override public boolean apply(Request<?> request) { // do I have to cancel this? return true; // -> always yes } }); }
這樣你就沒必要擔憂在onResponse被調用的時候用戶已經銷燬Activity。這種狀況下會拋出NullPointerException 異。可是post請求則須要繼續,即便用戶已經改變了Activity。咱們能夠經過使用tag來作到,在構造GET請求的時候,添加一個tag給它。
// after declaring your request request.setTag("My Tag"); mRequestQueue.add(request);
若是要取消全部指定標記My Tag的請求,只需簡單的添加下面的一行代碼:
mRequestQueue.cancelAll("My Tag");
這樣你就只會取消My Tag請求,讓其它請求不受影響。注意你必須手動在銷燬的Activity中處理這種狀況。
@Override rotected void onStop() { // TODO Auto-generated method stub super.onStop(); mRequestQueue.cancelAll( new RequestFilter() {}); or mRequestQueue.cancelAll(new Object());
Volley源碼下載:http://download.csdn.net/detail/shark0017/8404451