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); }