volley 之get、put、post、delete
Google released Android Volley Library around May/June 2013, which has been internally used by Google for some time. It is supposed to provide Fast Networking Operations and also takes care of Threads nicely. If you are unfamiliar with Volley, please see Google I/O 2013 Video
Unfortunately, there is almost no documentation on Volley. So, I put together code snippets on how to make Volley HTTP Requests (GET, POST, PUT, DELETE).
Setting up Android Volley Library
Setting up is straight-forward. Clone the Volley project from here and then import the Volley into project. A comprehensive tutorial on setting up can be found here.
Key Classes of Android Volley
The following are the Key classes of Volley:
- - RequestQueue: A Queue containing the Network/HTTP Requests that needs to be made.
- - Request: A Base Class which contains Network related information like HTTP Methods.
- - StringRequest: HTTP Request where the response is parsed a String. View Source
- - JsonObjectRequest: HTTP Request where the response is JSONObject. View Source
Getting Started with Android Volley
At first make a RequestQueue, which holds the HTTP Requests.
1 |
RequestQueue
queue = Volley.newRequestQueue( this );
//
this = context
|
Making GET Requests
Making GET Requests is simple. The example below uses JsonObjectRequest. It prepares a JsonObjectRequest and passes and then adds it to RequestQueue. The JsonObject accepts 4 parameters (Http method, Url, Json values, Response Listener - Invoked on success, Error Listener - Invoked on failure).
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//
prepare the Request
JsonObjectRequest
getRequest = new
JsonObjectRequest(Request.Method.GET, url, null ,
new
Response.Listener<JSONObject>()
{
@Override
public
void
onResponse(JSONObject response) {
//
display response
Log.d( "Response" ,
response.toString());
}
},
new
Response.ErrorListener()
{
@Override
public
void
onErrorResponse(VolleyError error) {
Log.d(
|