什么是volley
Volley 是一个 HTTP 库,它能够帮助 Android app 更方便地执行网络操作,最重要的是,它更快速高效,支持高并发网络连接。
使用volley
- 在manifest中添加android.permission.INTERNET
- 使用newRequestQuence发送post
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST,httpurl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "response -> " + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put("name1", "value1");
map.put("name2", "value2");
return params;
}
};
requestQueue.add(stringRequest);
使用httpClient发送post请求,和volley作对比
NameValuePair pair1 = new BasicNameValuePair("username", name);
NameValuePair pair2 = new BasicNameValuePair("age", age);
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(pair1);
pairList.add(pair2);
HttpEntity requestHttpEntity = new UrlEncodedFormEntity(pairList);
HttpPost httpPost = new HttpPost(baseURL);
httpPost.setEntity(requestHttpEntity);
HttpClient httpClient = new DefaultHttpClient();
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 显示响应
showResponseResult(response);