Volley Post网络请求

/*post请求*/
public void dostringVolleypost(){
/*第一步,创建请求队列*/
queue = Volley.newRequestQueue(this);
/*第二步,创建请求对象*/
StringRequest stringRequest = new StringRequest(
Request.Method.POST, //当改成post方法时:Request.Method.POST
"http://apis.baidu.com/txapi/tiyu/tiyu?num=10",
new Response.Listener<String>() {

@Override
public void onResponse(String response) {
String s = response;
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDefaultTextEncodingName("UTF-8");
webView.loadDataWithBaseURL(null,s,"text/html","UTF-8",null);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
webView.loadDataWithBaseURL(null,"网络请求失败","text/html","UTF-8",null);
}
}
){ //通过匿名内部类的方式实现post方法存储参数,其它的与get方法相同
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("name","ZhangSan");
map.put("pwd","123456");
return map;
}

/*getHeaders匿名内部类,获取头部,即获取apikey,对get方法和post方法都适用*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> map = new HashMap<String, String>();
map.put("apikey","96c52acc3831b95cf4a5c6f0e23ea209");
return map;
}
/*重写方法,完成转码*/
@Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
try {
String jsonObject = new String(new String(response.data, "UTF-8"));
return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (Exception je) {
return Response.error(new ParseError(je));
}
}
/*设置当前请求的优先级*/
@Override
public Priority getPriority() {
return Priority.HIGH;
}
};
stringRequest.setTag("post");
/*第三步,把请求对象放在请求队列*/
queue.add(stringRequest);
}

@Override
protected void onStop() {
super.onStop();
queue.cancelAll("get");/*取消当前队列里的Tag为get的请求*/
queue.cancelAll(this);/*取消当前队列里的所有网络请求*/
}
posted @ 2016-09-22 09:58  叶小龙  阅读(247)  评论(0编辑  收藏  举报