Volley Post请求
1、使用StringRequest,返回值是string
2、使用JsonObjectRequest,返回值是json
3、使用普通方式post请求,复杂繁琐,不建议。
1、使用StringRequest
使用结构
new StringRequest(访问方式,访问地址, 访问成功监听,访问失败监听){
//访问参数
protected Map<String, String> getParams() throws AuthFailureError{
//在这里使用map以键值对的顺序指定参数,并且参数的顺序不能乱,要按照访问地址的顺序依次添加。
比如访问地址为: www.baidu?参数1&参数2&参数3
那么map的添加顺序必须是:
map.put("参数1的键","参数1的值");
map.put("参数2的键","参数2的值");
map.put("参数3的键","参数3的值");
}
}
代码示例:
//1、定义访问地址
String urlString = "";
//2、实例化一个StringRequest
StringRequest request = new StringRequest(
Method.POST, //访问方式为post
urlString, //访问地址
new Listener<String>() {//访问成功的监听
//重写里面的onResponse方法
public void onResponse(String response) {
Toast.makeText(MainActivity.this, "访问成功", Toast.LENGTH_SHORT).show();
//response就是访问成功的返回值
};
},
new Response.ErrorListener() {//访问失败的监听
@Override//重写onErrorResponse
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
};
});
// post请求必须实现getParams()方法
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> hashMap = new HashMap<String, String>();
//使用map添加参数
hashMap.put("phone", "12345678900");
hashMap.put("key", "1235649741286315997");
//返回map
return hashMap;
}
};
//设置这个访问的唯一标识
request.setTag("lhdpost");
//将这个request添加到全局的volley请求队列,参照Volley的使用(一)
MyApplication.getHttpQueues().add(request);
}
2、使用JsonObjectRequest
String urlString = "";
/*JsonObjectRequest*/
//与StringRequest的不同点是,我们需要把访问参数封装在一个JSONObject对象内,然后提交给JsonObjectRequest请求队列。
//同样使用map来存放请求参数
HashMap<String, String>map = new HashMap<String,String>();
map.put("phone", "13023193686");
map.put("key", "335adcc4e891ba4e4be6d7534fd54c5d");
//建立JSONObject,将map作为参数传入
JSONObject object = new JSONObject(map);
//将JSONObject作为,将上一步得到的JSONObject对象作为参数传入
JsonObjectRequest objectRequest = new JsonObjectRequest(Method.POST,urlString, object,
new Listener<JSONObject>() {//访问成功的监听
@Override
public void onResponse(JSONObject response) {
//得到的response,即是返回的json字符串,解析即可得到数据
Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
};
},
new Response.ErrorListener() {//访问失败的监听
public void onErrorResponse(VolleyError error){
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
};
}
);
//添加唯一标识
objectRequest.setTag("lhdpost");
//将请求添加到请求队列
MyApplication.getHttpQueues().add(objectRequest);