HttpPost和HttpGet对象为url以便能够与Volley一起使用?

时间:2014-09-17 09:58:26

标签: java android apache android-volley

Volley为我们提供了更高的效率,但是它使用了" url"

JsonObjectRequest j = new JsonObjectRequest((int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener);

但是如果我必须使用HttpPost或HttpGet对象,因为我必须设置Header和Entity等。如何在仍然使用Volley时这样做。

HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("String", "something" );
httpGet.setHeader("Content-Type","application/json");
...
httpPost.setEntity(new StringEntity("whatever"));

基本上在这些代码行之后我得到了HttpPost / HttpGet对象;有没有办法在volley中使用这个对象,而不是使用HttpClient来执行请求。

或者是否有一些不同的方法来设置标题等,然后将它与Volley一起使用。

2 个答案:

答案 0 :(得分:1)

覆盖Volley请求对象中的getHeaders()方法。然后返回一个包含该方法标题的地图。

答案 1 :(得分:1)

我认为它可以帮助你理解:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                                Request.Method.POST,
                                url,
                                jsonRequest,
                                new JSONResponseListener(this),
                                new JSONResponseErrorListener(this)){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }

        @Override
        protected Map<String, String> getParams()  {
            Map<String, String> params = new HashMap<String, String>();
            params.put("username", username);
            params.put("password", password);

            return params;
        }
    };
    MyApplication.getInstance().addToRequestQueue(jsonObjectRequest);