Volley是一个模块,封装好了jar包,可以很方便的发送http请求和处理http请求。
先需要下载Volley.java。下载地址:点击下载
然后将Volley.jar复制到工程中,再add to library。
RequestQueue:字面意思为请求队列。由于RequestQueue内部已经处理好了高并发,所以我们可以为所有的请求共用一个RequestQueue【请求队列】。
StringRequest:具体的请求信息。
在MainActivity.java中:
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest("http://www.baidu.com",
new Response.Listener<String>() {
@Override
public void onResponse(String string) {
Log.d("MainActivity", string);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("MainActivity", volleyError.getMessage(), volleyError);
}
}
);
requestQueue.add(stringRequest);
效果如下:
简单的发送一条http请求,获得了百度首页的源码。就这么实现了。
发送POST请求:
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://115.159.30.17/IHelpYou/Login",
new Response.Listener<String>() {
public void onResponse(String response) {
Log.d("TAG", response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}
) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("phone", "13530536529");
map.put("password", "123456");
return map;
}
};
requestQueue.add(stringRequest);
这样的话 效果可就高多了。
更重要的是Volley支持json数据:
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://image.baidu.com/search/avatarjson?tn=resultjsonavatarnew&ie=utf-8&word=%E7%99%BE%E5%BA%A6", null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
requestQueue.add(jsonObjectRequest);
效果:
当然也可以重写protected Map<String, String> getParams()方法增加请求参数。