volley中网络请求
首先使用Volley类创建 RequestQueue queue = Volley.newRequestQueue(
this
);
Making GET Requests
1 final String url = "http://httpbin.org/get?param1=hello"; 2 3 // prepare the Request 4 JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null, 5 new Response.Listener<JSONObject>() 6 { 7 @Override 8 public void onResponse(JSONObject response) { 9 // display response 10 Log.d("Response", response.toString()); 11 } 12 }, 13 new Response.ErrorListener() 14 { 15 @Override 16 public void onErrorResponse(VolleyError error) { 17 Log.d("Error.Response", response); 18 } 19 } 20 ); 21 22 // add it to the RequestQueue 23 queue.add(getRequest);
Making POST Requests
1 url = "http://httpbin.org/post"; 2 StringRequest postRequest = new StringRequest(Request.Method.POST, url, 3 new Response.Listener<String>() 4 { 5 @Override 6 public void onResponse(String response) { 7 // response 8 Log.d("Response", response); 9 } 10 }, 11 new Response.ErrorListener() 12 { 13 @Override 14 public void onErrorResponse(VolleyError error) { 15 // error 16 Log.d("Error.Response", response); 17 } 18 } 19 ) { 20 @Override 21 protected Map<String, String> getParams() 22 { 23 Map<String, String> params = new HashMap<String, String>(); 24 params.put("name", "Alif"); 25 params.put("domain", "http://itsalif.info"); 26 27 return params; 28 } 29 }; 30 queue.add(postRequest);
Making PUT Requests
1 url = "http://httpbin.org/put"; 2 StringRequest putRequest = new StringRequest(Request.Method.PUT, url, 3 new Response.Listener<String>() 4 { 5 @Override 6 public void onResponse(String response) { 7 // response 8 Log.d("Response", response); 9 } 10 }, 11 new Response.ErrorListener() 12 { 13 @Override 14 public void onErrorResponse(VolleyError error) { 15 // error 16 Log.d("Error.Response", response); 17 } 18 } 19 ) { 20 21 @Override 22 protected Map<String, String> getParams() 23 { 24 Map<String, String> params = new HashMap<String, String> (); 25 params.put("name", "Alif"); 26 params.put("domain", "http://itsalif.info"); 27 28 return params; 29 } 30 31 }; 32 33 queue.add(putRequest);
Making DELETE Requests
1 url = "http://httpbin.org/delete"; 2 StringRequest dr = new StringRequest(Request.Method.DELETE, url, 3 new Response.Listener<String>() 4 { 5 @Override 6 public void onResponse(String response) { 7 // response 8 Toast.makeText($this, response, Toast.LENGTH_LONG).show(); 9 } 10 }, 11 new Response.ErrorListener() 12 { 13 @Override 14 public void onErrorResponse(VolleyError error) { 15 // error. 16 17 } 18 } 19 ); 20 queue.add(dr);
下一篇继续介绍Volley图片加载............