public class VolleyActivity extends AppCompatActivity {
WebView webView;
Button button;
RequestQueue queue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
webView = (WebView) findViewById(R.id.web);
button = (Button) findViewById(R.id.volleybtn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dostringVolley();
}
});
}
/*get请求*/
public void dostringVolley(){
/*第一步,创建请求队列*/
queue = Volley.newRequestQueue(this);
/*第二步,创建请求对象*/
StringRequest stringRequest = new StringRequest(
Request.Method.GET, //当改成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);
}
}
)
/*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.LOW;
}
};
stringRequest.setTag("get");
/*第三步,把请求对象放在请求队列*/
queue.add(stringRequest);
}