> queue, Network network,
60 | Cache cache, ResponseDelivery delivery) {
61 | mQueue = queue;
62 | mNetwork = network;
63 | mCache = cache;
64 | mDelivery = delivery;
65 | }
66 |
67 | /**
68 | * Forces this dispatcher to quit immediately. If any requests are still in
69 | * the queue, they are not guaranteed to be processed.
70 | */
71 | public void quit() {
72 | mQuit = true;
73 | interrupt();
74 | }
75 |
76 | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
77 | private void addTrafficStatsTag(Request> request) {
78 | // Tag the request (if API >= 14)
79 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
80 | TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
81 | }
82 | }
83 |
84 | @Override
85 | public void run() {
86 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
87 | Request> request;
88 | while (true) {
89 | try {
90 | // Take a request from the queue.
91 | request = mQueue.take();
92 | } catch (InterruptedException e) {
93 | // We may have been interrupted because it was time to quit.
94 | if (mQuit) {
95 | return;
96 | }
97 | continue;
98 | }
99 |
100 | try {
101 | request.addMarker("network-queue-take");
102 |
103 | // If the request was cancelled already, do not perform the
104 | // network request.
105 | if (request.isCanceled()) {
106 | request.finish("network-discard-cancelled");
107 | continue;
108 | }
109 |
110 | addTrafficStatsTag(request);
111 |
112 | // Perform the network request.
113 | // �������磬�õ�����
114 | NetworkResponse networkResponse = mNetwork
115 | .performRequest(request);
116 | request.addMarker("network-http-complete");
117 |
118 | // If the server returned 304 AND we delivered a response
119 | // already,
120 | // we're done -- don't deliver a second identical response.
121 | if (networkResponse.notModified
122 | && request.hasHadResponseDelivered()) {
123 | request.finish("not-modified");
124 | continue;
125 | }
126 |
127 | // Parse the response here on the worker thread.
128 | Response> response = request
129 | .parseNetworkResponse(networkResponse);
130 | request.addMarker("network-parse-complete");
131 | // д�뻺��
132 | // Write to cache if applicable.
133 | // TODO: Only update cache metadata instead of entire record for
134 | // 304s.
135 | if (request.shouldCache() && response.cacheEntry != null) {
136 | mCache.put(request.getCacheKey(), response.cacheEntry);
137 | request.addMarker("network-cache-written");
138 | }
139 |
140 | // Post the response back.
141 | request.markDelivered();
142 | mDelivery.postResponse(request, response);
143 | } catch (VolleyError volleyError) {
144 | parseAndDeliverNetworkError(request, volleyError);
145 | } catch (Exception e) {
146 | VolleyLog.e(e, "Unhandled exception %s", e.toString());
147 | mDelivery.postError(request, new VolleyError(e));
148 | }
149 | }
150 | }
151 |
152 | private void parseAndDeliverNetworkError(Request> request,
153 | VolleyError error) {
154 | error = request.parseNetworkError(error);
155 | mDelivery.postError(request, error);
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/Volley/src/com/android/volley/toolbox/ByteArrayPool.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2012 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley.toolbox;
18 |
19 | import java.util.ArrayList;
20 | import java.util.Collections;
21 | import java.util.Comparator;
22 | import java.util.LinkedList;
23 | import java.util.List;
24 |
25 | /**
26 | * ByteArrayPool is a source and repository of byte[] objects. Its purpose is to
27 | * supply those buffers to consumers who need to use them for a short period of time and then
28 | * dispose of them. Simply creating and disposing such buffers in the conventional manner can
29 | * considerable heap churn and garbage collection delays on Android, which lacks good management of
30 | * short-lived heap objects. It may be advantageous to trade off some memory in the form of a
31 | * permanently allocated pool of buffers in order to gain heap performance improvements; that is
32 | * what this class does.
33 | *
34 | * A good candidate user for this class is something like an I/O system that uses large temporary
35 | * byte[] buffers to copy data around. In these use cases, often the consumer wants
36 | * the buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks
37 | * off of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into
38 | * account and also to maximize the odds of being able to reuse a recycled buffer, this class is
39 | * free to return buffers larger than the requested size. The caller needs to be able to gracefully
40 | * deal with getting buffers any size over the minimum.
41 | *
42 | * If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this
43 | * class will allocate a new buffer and return it.
44 | *
45 | * This class has no special ownership of buffers it creates; the caller is free to take a buffer
46 | * it receives from this pool, use it permanently, and never return it to the pool; additionally,
47 | * it is not harmful to return to this pool a buffer that was allocated elsewhere, provided there
48 | * are no other lingering references to it.
49 | *
50 | * This class ensures that the total size of the buffers in its recycling pool never exceeds a
51 | * certain byte limit. When a buffer is returned that would cause the pool to exceed the limit,
52 | * least-recently-used buffers are disposed.
53 | */
54 | public class ByteArrayPool {
55 | /** The buffer pool, arranged both by last use and by buffer size */
56 | private List mBuffersByLastUse = new LinkedList();
57 | private List mBuffersBySize = new ArrayList(64);
58 |
59 | /** The total size of the buffers in the pool */
60 | private int mCurrentSize = 0;
61 |
62 | /**
63 | * The maximum aggregate size of the buffers in the pool. Old buffers are discarded to stay
64 | * under this limit.
65 | */
66 | private final int mSizeLimit;
67 |
68 | /** Compares buffers by size */
69 | protected static final Comparator BUF_COMPARATOR = new Comparator() {
70 | @Override
71 | public int compare(byte[] lhs, byte[] rhs) {
72 | return lhs.length - rhs.length;
73 | }
74 | };
75 |
76 | /**
77 | * @param sizeLimit the maximum size of the pool, in bytes
78 | */
79 | public ByteArrayPool(int sizeLimit) {
80 | mSizeLimit = sizeLimit;
81 | }
82 |
83 | /**
84 | * Returns a buffer from the pool if one is available in the requested size, or allocates a new
85 | * one if a pooled one is not available.
86 | *
87 | * @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be
88 | * larger.
89 | * @return a byte[] buffer is always returned.
90 | */
91 | public synchronized byte[] getBuf(int len) {
92 | for (int i = 0; i < mBuffersBySize.size(); i++) {
93 | byte[] buf = mBuffersBySize.get(i);
94 | if (buf.length >= len) {
95 | mCurrentSize -= buf.length;
96 | mBuffersBySize.remove(i);
97 | mBuffersByLastUse.remove(buf);
98 | return buf;
99 | }
100 | }
101 | return new byte[len];
102 | }
103 |
104 | /**
105 | * Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted
106 | * size.
107 | *
108 | * @param buf the buffer to return to the pool.
109 | */
110 | public synchronized void returnBuf(byte[] buf) {
111 | if (buf == null || buf.length > mSizeLimit) {
112 | return;
113 | }
114 | mBuffersByLastUse.add(buf);
115 | int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
116 | if (pos < 0) {
117 | pos = -pos - 1;
118 | }
119 | mBuffersBySize.add(pos, buf);
120 | mCurrentSize += buf.length;
121 | trim();
122 | }
123 |
124 | /**
125 | * Removes buffers from the pool until it is under its size limit.
126 | */
127 | private synchronized void trim() {
128 | while (mCurrentSize > mSizeLimit) {
129 | byte[] buf = mBuffersByLastUse.remove(0);
130 | mBuffersBySize.remove(buf);
131 | mCurrentSize -= buf.length;
132 | }
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/Volley/src/com/android/volley/CacheDispatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import android.os.Process;
20 |
21 | import java.util.concurrent.BlockingQueue;
22 |
23 | /**
24 | * Provides a thread for performing cache triage on a queue of requests.
25 | *
26 | * Requests added to the specified cache queue are resolved from cache.
27 | * Any deliverable response is posted back to the caller via a
28 | * {@link ResponseDelivery}. Cache misses and responses that require
29 | * refresh are enqueued on the specified network queue for processing
30 | * by a {@link NetworkDispatcher}.
31 | */
32 | public class CacheDispatcher extends Thread {
33 |
34 | private static final boolean DEBUG = VolleyLog.DEBUG;
35 |
36 | /** The queue of requests coming in for triage. */
37 | private final BlockingQueue> mCacheQueue;
38 |
39 | /** The queue of requests going out to the network. */
40 | private final BlockingQueue> mNetworkQueue;
41 |
42 | /** The cache to read from. */
43 | private final Cache mCache;
44 |
45 | /** For posting responses. */
46 | private final ResponseDelivery mDelivery;
47 |
48 | /** Used for telling us to die. */
49 | private volatile boolean mQuit = false;
50 |
51 | /**
52 | * Creates a new cache triage dispatcher thread. You must call {@link #start()}
53 | * in order to begin processing.
54 | *
55 | * @param cacheQueue Queue of incoming requests for triage
56 | * @param networkQueue Queue to post requests that require network to
57 | * @param cache Cache interface to use for resolution
58 | * @param delivery Delivery interface to use for posting responses
59 | */
60 | public CacheDispatcher(
61 | BlockingQueue> cacheQueue, BlockingQueue> networkQueue,
62 | Cache cache, ResponseDelivery delivery) {
63 | mCacheQueue = cacheQueue;
64 | mNetworkQueue = networkQueue;
65 | mCache = cache;
66 | mDelivery = delivery;
67 | }
68 |
69 | /**
70 | * Forces this dispatcher to quit immediately. If any requests are still in
71 | * the queue, they are not guaranteed to be processed.
72 | */
73 | public void quit() {
74 | mQuit = true;
75 | interrupt();
76 | }
77 |
78 | @Override
79 | public void run() {
80 | if (DEBUG) VolleyLog.v("start new dispatcher");
81 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
82 | // Make a blocking call to initialize the cache.
83 | mCache.initialize();
84 |
85 | while (true) {
86 | try {
87 | // Get a request from the cache triage queue, blocking until
88 | // at least one is available.
89 | final Request> request = mCacheQueue.take();
90 | request.addMarker("cache-queue-take");
91 | // If the request has been canceled, don't bother dispatching it.
92 |
93 | if (request.isCanceled()) {
94 | request.finish("cache-discard-canceled");
95 | continue;
96 | }
97 |
98 | // Attempt to retrieve this item from cache.
99 | Cache.Entry entry = mCache.get(request.getCacheKey());
100 | if (entry == null) {
101 | request.addMarker("cache-miss");
102 | // Cache miss; send off to the network dispatcher.
103 | mNetworkQueue.put(request);
104 | continue;
105 | }
106 |
107 | // If it is completely expired, just send it to the network.
108 | if (entry.isExpired()) {
109 | request.addMarker("cache-hit-expired");
110 | request.setCacheEntry(entry);
111 | mNetworkQueue.put(request);
112 | continue;
113 | }
114 |
115 | // We have a cache hit; parse its data for delivery back to the request.
116 | request.addMarker("cache-hit");
117 | Response> response = request.parseNetworkResponse(
118 | new NetworkResponse(entry.data, entry.responseHeaders));
119 | request.addMarker("cache-hit-parsed");
120 |
121 | if (!entry.refreshNeeded()) {
122 | // Completely unexpired cache hit. Just deliver the response.
123 | mDelivery.postResponse(request, response);
124 | } else {
125 | // Soft-expired cache hit. We can deliver the cached response,
126 | // but we need to also send the request to the network for
127 | // refreshing.
128 | request.addMarker("cache-hit-refresh-needed");
129 | request.setCacheEntry(entry);
130 |
131 | // Mark the response as intermediate.
132 | response.intermediate = true;
133 |
134 | // Post the intermediate response back to the user and have
135 | // the delivery then forward the request along to the network.
136 | mDelivery.postResponse(request, response, new Runnable() {
137 | @Override
138 | public void run() {
139 | try {
140 | mNetworkQueue.put(request);
141 | } catch (InterruptedException e) {
142 | // Not much we can do about this.
143 | }
144 | }
145 | });
146 | }
147 |
148 | } catch (InterruptedException e) {
149 | // We may have been interrupted because it was time to quit.
150 | if (mQuit) {
151 | return;
152 | }
153 | continue;
154 | }
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/Volley/src/com/android/volley/VolleyLog.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2011 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.android.volley;
18 |
19 | import android.os.SystemClock;
20 | import android.util.Log;
21 |
22 | import java.util.ArrayList;
23 | import java.util.List;
24 | import java.util.Locale;
25 |
26 | /** Logging helper class. */
27 | public class VolleyLog {
28 | public static String TAG = "Volley";
29 |
30 | public static boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
31 |
32 | /**
33 | * Customize the log tag for your application, so that other apps
34 | * using Volley don't mix their logs with yours.
35 | *
36 | * Enable the log property for your tag before starting your app:
37 | *
38 | * {@code adb shell setprop log.tag.<tag>}
39 | */
40 | public static void setTag(String tag) {
41 | d("Changing log tag to %s", tag);
42 | TAG = tag;
43 |
44 | // Reinitialize the DEBUG "constant"
45 | DEBUG = Log.isLoggable(TAG, Log.VERBOSE);
46 | }
47 |
48 | public static void v(String format, Object... args) {
49 | if (DEBUG) {
50 | Log.v(TAG, buildMessage(format, args));
51 | }
52 | }
53 |
54 | public static void d(String format, Object... args) {
55 | Log.d(TAG, buildMessage(format, args));
56 | }
57 |
58 | public static void e(String format, Object... args) {
59 | Log.e(TAG, buildMessage(format, args));
60 | }
61 |
62 | public static void e(Throwable tr, String format, Object... args) {
63 | Log.e(TAG, buildMessage(format, args), tr);
64 | }
65 |
66 | public static void wtf(String format, Object... args) {
67 | Log.wtf(TAG, buildMessage(format, args));
68 | }
69 |
70 | public static void wtf(Throwable tr, String format, Object... args) {
71 | Log.wtf(TAG, buildMessage(format, args), tr);
72 | }
73 |
74 | /**
75 | * Formats the caller's provided message and prepends useful info like
76 | * calling thread ID and method name.
77 | */
78 | private static String buildMessage(String format, Object... args) {
79 | String msg = (args == null) ? format : String.format(Locale.US, format, args);
80 | StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace();
81 |
82 | String caller = "";
83 | // Walk up the stack looking for the first caller outside of VolleyLog.
84 | // It will be at least two frames up, so start there.
85 | for (int i = 2; i < trace.length; i++) {
86 | Class> clazz = trace[i].getClass();
87 | if (!clazz.equals(VolleyLog.class)) {
88 | String callingClass = trace[i].getClassName();
89 | callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1);
90 | callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1);
91 |
92 | caller = callingClass + "." + trace[i].getMethodName();
93 | break;
94 | }
95 | }
96 | return String.format(Locale.US, "[%d] %s: %s",
97 | Thread.currentThread().getId(), caller, msg);
98 | }
99 |
100 | /**
101 | * A simple event log with records containing a name, thread ID, and timestamp.
102 | */
103 | static class MarkerLog {
104 | public static final boolean ENABLED = VolleyLog.DEBUG;
105 |
106 | /** Minimum duration from first marker to last in an marker log to warrant logging. */
107 | private static final long MIN_DURATION_FOR_LOGGING_MS = 0;
108 |
109 | private static class Marker {
110 | public final String name;
111 | public final long thread;
112 | public final long time;
113 |
114 | public Marker(String name, long thread, long time) {
115 | this.name = name;
116 | this.thread = thread;
117 | this.time = time;
118 | }
119 | }
120 |
121 | private final List mMarkers = new ArrayList();
122 | private boolean mFinished = false;
123 |
124 | /** Adds a marker to this log with the specified name. */
125 | public synchronized void add(String name, long threadId) {
126 | if (mFinished) {
127 | throw new IllegalStateException("Marker added to finished log");
128 | }
129 |
130 | mMarkers.add(new Marker(name, threadId, SystemClock.elapsedRealtime()));
131 | }
132 |
133 | /**
134 | * Closes the log, dumping it to logcat if the time difference between
135 | * the first and last markers is greater than {@link #MIN_DURATION_FOR_LOGGING_MS}.
136 | * @param header Header string to print above the marker log.
137 | */
138 | public synchronized void finish(String header) {
139 | mFinished = true;
140 |
141 | long duration = getTotalDuration();
142 | if (duration <= MIN_DURATION_FOR_LOGGING_MS) {
143 | return;
144 | }
145 |
146 | long prevTime = mMarkers.get(0).time;
147 | d("(%-4d ms) %s", duration, header);
148 | for (Marker marker : mMarkers) {
149 | long thisTime = marker.time;
150 | d("(+%-4d) [%2d] %s", (thisTime - prevTime), marker.thread, marker.name);
151 | prevTime = thisTime;
152 | }
153 | }
154 |
155 | @Override
156 | protected void finalize() throws Throwable {
157 | // Catch requests that have been collected (and hence end-of-lifed)
158 | // but had no debugging output printed for them.
159 | if (!mFinished) {
160 | finish("Request on the loose");
161 | e("Marker log finalized without finish() - uncaught exit point for request");
162 | }
163 | }
164 |
165 | /** Returns the time difference between the first and last events in this log. */
166 | private long getTotalDuration() {
167 | if (mMarkers.size() == 0) {
168 | return 0;
169 | }
170 |
171 | long first = mMarkers.get(0).time;
172 | long last = mMarkers.get(mMarkers.size() - 1).time;
173 | return last - first;
174 | }
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/VolleyDemo/src/com/example/volley_demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.volley_demo;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.widget.TextView;
9 | import android.widget.Toast;
10 |
11 | import com.android.volley.AuthFailureError;
12 | import com.android.volley.Request.Method;
13 | import com.android.volley.Response;
14 | import com.android.volley.VolleyError;
15 | import com.android.volley.toolbox.JsonObjectRequest;
16 | import com.android.volley.toolbox.StringRequest;
17 |
18 | import org.json.JSONObject;
19 |
20 | import java.io.UnsupportedEncodingException;
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | import static com.example.volley_demo.Constants.URL;
25 |
26 |
27 | public class MainActivity extends Activity implements View.OnClickListener{
28 |
29 | private final String TAG = "MainActivity";
30 | private String url = URL;
31 | private Response.ErrorListener errorListener = new Response.ErrorListener() {
32 | @Override
33 | public void onErrorResponse(VolleyError error) { //数据请求失败返回
34 | Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
35 | }
36 | };
37 |
38 | @Override
39 | public void onClick(View v) {
40 | switch (v.getId()){
41 | case R.id.gotoimg:
42 | startActivity(new Intent(MainActivity.this, ImageActivity.class));
43 | break;
44 | case R.id.volleyStringGet:
45 | volleyStringGet();
46 | break;
47 | case R.id.volleyJsonObjectGet:
48 | volleyJsonObjectGet();
49 | break;
50 | case R.id.volleyCustomGet:
51 | volleyCustomGet();
52 | break;
53 | case R.id.volleyStringPost:
54 | volleyStringPost();
55 | break;
56 | case R.id.volleyJsonObjectPost:
57 | volleyJsonObjectPost();
58 | break;
59 | default:
60 | break;
61 | }
62 | }
63 |
64 | @Override
65 | protected void onCreate(Bundle savedInstanceState) {
66 | super.onCreate(savedInstanceState);
67 | setContentView(R.layout.activity_main);
68 | findViewById(R.id.gotoimg).setOnClickListener(this);
69 | findViewById(R.id.volleyStringGet).setOnClickListener(this);
70 | findViewById(R.id.volleyJsonObjectGet).setOnClickListener(this);
71 | findViewById(R.id.volleyCustomGet).setOnClickListener(this);
72 | findViewById(R.id.volleyStringPost).setOnClickListener(this);
73 | findViewById(R.id.volleyJsonObjectPost).setOnClickListener(this);
74 | }
75 |
76 |
77 | /**
78 | * get请求String
79 | */
80 | private void volleyStringGet(){
81 | Response.Listener listener = new Response.Listener() {
82 | @Override
83 | public void onResponse(String response) { //数据请求成功返回
84 | Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
85 | }
86 | };
87 | StringRequest request = new StringRequest(Method.GET, url, listener, errorListener);
88 | request.setTag("jackStringRequest");
89 | MyApplication.getHttpRequestQueue().add(request);
90 | }
91 |
92 | /**
93 | * get请求jsonobject
94 | */
95 | private void volleyJsonObjectGet(){
96 | Response.Listener listener = new Response.Listener() {
97 | @Override
98 | public void onResponse(JSONObject response) {
99 | Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
100 | Log.d(TAG, "JSONObject-----------" + response.toString());
101 | }
102 | };
103 | JsonObjectRequest request = new JsonObjectRequest(Method.GET, url, null, listener, errorListener);
104 | request.setTag("jackJsonObjectRequest");
105 | MyApplication.getHttpRequestQueue().add(request);
106 | }
107 |
108 | /**
109 | * 使用自定义的get方式请求数据,二次封装
110 | */
111 | private void volleyCustomGet(){
112 | CustomVolleyRequest.requestGet(url, "volleyCustomGet", new VolleyListener(this,
113 | VolleyListener.mListener, VolleyListener.mErrorListener) {
114 | @Override
115 | public void onMySuccess(String response) {
116 | Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
117 | Log.d(TAG, "volleyCustomGet-----" + response);
118 | }
119 |
120 | @Override
121 | public void onMyError(VolleyError error) {
122 | Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
123 | Log.d(TAG, "volleyCustomGet error-----" + error.getMessage());
124 | }
125 | });
126 | }
127 |
128 |
129 |
130 | /**
131 | * todo 服务器需要能够解析json参数
132 | */
133 | private void volleyJsonObjectPost(){
134 | String url = "http://apis.juhe.cn/mobile/get?";
135 | Response.Listener listener = new Response.Listener(){
136 | @Override
137 | public void onResponse(JSONObject response) {
138 | if(response != null){
139 | Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
140 | Log.d(TAG, "volleyJsonObjectPost----" + response.toString());
141 | }
142 | }
143 | };
144 |
145 | final String requestBody = "phone=13811253688&key=cf365ff9aa9f1daddea8357b43267fd7";
146 | JsonObjectRequest request = new JsonObjectRequest(Method.POST, url, null,
147 | listener, errorListener){
148 |
149 | @Override
150 | public byte[] getPostBody() {
151 | return getBody();
152 | }
153 |
154 | @Override
155 | public byte[] getBody() {
156 | try {
157 | return requestBody.toString().getBytes("UTF-8");
158 | } catch (UnsupportedEncodingException e) {
159 | e.printStackTrace();
160 | }
161 | return null;
162 | }
163 | };
164 | request.setTag("jsonPost");
165 | MyApplication.getHttpRequestQueue().add(request);
166 | }
167 |
168 |
169 | /**
170 | * post请求
171 | */
172 | private void volleyStringPost() {
173 | String url = "http://apis.juhe.cn/mobile/get?";
174 | Response.Listener listener = new Response.Listener() {
175 | @Override
176 | public void onResponse(String response) {
177 | if(response != null) {
178 | Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
179 | Log.d(TAG, "JSONObject-----------" + response.toString());
180 | }
181 | }
182 | };
183 | StringRequest request = new StringRequest(Method.POST, url, listener, errorListener){
184 | @Override
185 | protected Map getParams() throws AuthFailureError {
186 | Map hashMap = new HashMap();
187 | hashMap.put("phone", "13811253688");
188 | hashMap.put("key", "cf365ff9aa9f1daddea8357b43267fd7");
189 | return hashMap;
190 | }
191 | };
192 | request.setTag("jackPost");
193 | MyApplication.getHttpRequestQueue().add(request);
194 | }
195 |
196 | @Override
197 | protected void onStop() {
198 | super.onStop();
199 | MyApplication.getHttpRequestQueue().cancelAll("jackStringRequest");
200 | MyApplication.getHttpRequestQueue().cancelAll("jackJsonObjectRequest");
201 | MyApplication.getHttpRequestQueue().cancelAll("jackPost");
202 | MyApplication.getHttpRequestQueue().cancelAll("jsonPost");
203 |
204 | }
205 | }
206 |
--------------------------------------------------------------------------------