如何在Volley请求中设置自定义标题

自定义标头如何设置为排气请求? 目前,可以为POST请求设置正文内容。 我有一个简单的GET请求,但我需要传递自定义标题。 我没有看到JsonRequest类如何支持它。 有没有可能?

它看起来像覆盖Request定义的 public Map<String, String> getHeaders() ,以返回所需的HTTP标头。

getParams()接受的答案是用于设置POST正文数据,但标题中的问题询问如何设置HTTP头像User-Agent。 正如CommonsWare所说,你重写getHeaders()。 下面是一些将User-Agent设置为“任天堂Gameboy”并将Accept-Language设置为“fr”的示例代码:

 public void requestWithSomeHttpHeaders() { RequestQueue queue = Volley.newRequestQueue(this); String url = "http://www.somewebsite.com"; StringRequest postRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub Log.d("ERROR","error => "+error.toString()); } } ) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("User-Agent", "Nintendo Gameboy"); params.put("Accept-Language", "fr"); return params; } }; queue.add(postRequest); } 

如果你需要的是发布数据,而不是在url中添加信息。

 public Request post(String url, String username, String password, Listener listener, ErrorListener errorListener) { JSONObject params = new JSONObject(); params.put("user", username); params.put("pass", password); Request req = new Request( Method.POST, url, params.toString(), listener, errorListener ); return req; } 

如果你想要做的是编辑请求中的头部,这是你想要做的:

 // could be any class that implements Map Map<String, String> mHeaders = new ArrayMap<String, String>(); mHeaders.put("user", USER); mHeaders.put("pass", PASSWORD); Request req = new Request(url, postBody, listener, errorListener) { public Map<String, String> getHeaders() { return mHeaders; } } 

你可以看到这个解决scheme。 它显示如何获取/设置Cookie,但Cookie只是请求/响应中的标题之一。 您必须重写一个Volley的* Request类,并在getHeaders()设置所需的标题


这是链接的来源:

 public class StringRequest extends com.android.volley.toolbox.StringRequest { private final Map<String, String> _params; /** * @param method * @param url * @param params * A {@link HashMap} to post with the request. Null is allowed * and indicates no parameters will be posted along with request. * @param listener * @param errorListener */ public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener, ErrorListener errorListener) { super(method, url, listener, errorListener); _params = params; } @Override protected Map<String, String> getParams() { return _params; } /* (non-Javadoc) * @see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse) */ @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { // since we don't know which of the two underlying network vehicles // will Volley use, we have to handle and store session cookies manually MyApp.get().checkSessionCookie(response.headers); return super.parseNetworkResponse(response); } /* (non-Javadoc) * @see com.android.volley.Request#getHeaders() */ @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = super.getHeaders(); if (headers == null || headers.equals(Collections.emptyMap())) { headers = new HashMap<String, String>(); } MyApp.get().addSessionCookie(headers); return headers; } 

}

和MyApp类:

 public class MyApp extends Application { private static final String SET_COOKIE_KEY = "Set-Cookie"; private static final String COOKIE_KEY = "Cookie"; private static final String SESSION_COOKIE = "sessionid"; private static MyApp _instance; private RequestQueue _requestQueue; private SharedPreferences _preferences; public static MyApp get() { return _instance; } @Override public void onCreate() { super.onCreate(); _instance = this; _preferences = PreferenceManager.getDefaultSharedPreferences(this); _requestQueue = Volley.newRequestQueue(this); } public RequestQueue getRequestQueue() { return _requestQueue; } /** * Checks the response headers for session cookie and saves it * if it finds it. * @param headers Response Headers. */ public final void checkSessionCookie(Map<String, String> headers) { if (headers.containsKey(SET_COOKIE_KEY) && headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) { String cookie = headers.get(SET_COOKIE_KEY); if (cookie.length() > 0) { String[] splitCookie = cookie.split(";"); String[] splitSessionId = splitCookie[0].split("="); cookie = splitSessionId[1]; Editor prefEditor = _preferences.edit(); prefEditor.putString(SESSION_COOKIE, cookie); prefEditor.commit(); } } } /** * Adds session cookie to headers if exists. * @param headers */ public final void addSessionCookie(Map<String, String> headers) { String sessionId = _preferences.getString(SESSION_COOKIE, ""); if (sessionId.length() > 0) { StringBuilder builder = new StringBuilder(); builder.append(SESSION_COOKIE); builder.append("="); builder.append(sessionId); if (headers.containsKey(COOKIE_KEY)) { builder.append("; "); builder.append(headers.get(COOKIE_KEY)); } headers.put(COOKIE_KEY, builder.toString()); } } } 

寻找这个问题的解决scheme。 看到这里的东西: http : //developer.android.com/training/volley/request.html

直接使用ImageRequest而不是ImageLoader是个好主意吗? 好像ImageLoader在内部使用它。 除了ImageLoader的caching支持以外,是否会丢失任何重要的内容?

 ImageView mImageView; String url = "http://i.imgur.com/7spzG.png"; mImageView = (ImageView) findViewById(R.id.myImage); ... // Retrieves an image specified by the URL, displays it in the UI. mRequestQueue = Volley.newRequestQueue(context);; ImageRequest request = new ImageRequest(url, new Response.Listener() { @Override public void onResponse(Bitmap bitmap) { mImageView.setImageBitmap(bitmap); } }, 0, 0, null, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { mImageView.setImageResource(R.drawable.image_load_error); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new Map<String, String>(); params.put("User-Agent", "one"); params.put("header22", "two"); return params; }; mRequestQueue.add(request); 

尝试这个

 { @Override public Map<String, String> getHeaders() throws AuthFailureError { String bearer = "Bearer ".concat(token); Map<String, String> headersSys = super.getHeaders(); Map<String, String> headers = new HashMap<String, String>(); headersSys.remove("Authorization"); headers.put("Authorization", bearer); headers.putAll(headersSys); return headers; } }; 

您可以创build一个自定义的Request类来扩展StringRequest并覆盖其中的getHeaders()方法,如下所示:

 public class CustomVolleyRequest extends StringRequest { public CustomVolleyRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); headers.put("key1","value1"); headers.put("key2","value2"); return headers; } } 
 public class CustomJsonObjectRequest extends JsonObjectRequest { public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest,Response.Listener listener, Response.ErrorListener errorListener) { super(method, url, jsonRequest, listener, errorListener); } @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap(); headers.put("AppId", "xyz"); return headers; } } 

这里是从github示例设置标题:

 StringRequest myReq = new StringRequest(Method.POST, "http://ave.bolyartech.com/params.php", createMyReqSuccessListener(), createMyReqErrorListener()) { protected Map<String, String> getParams() throws com.android.volley.AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put("param1", num1); params.put("param2", num2); return params; }; }; queue.add(myReq); 

尝试这个

  public void VolleyPostReqWithResponseListenerwithHeaders(String URL,final Map<String, String> params,final Map<String, String> headers,Response.Listener<String> responseListener) { String url = URL; Log.i("url:", ":" + url); StringRequest mStringRequest = new StringRequest(Request.Method.POST, url, responseListener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error //Log.d("Error.Response", error.getLocalizedMessage()); } }){ @Override protected Map<String, String> getParams() { return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return headers; } }; mStringRequest.setRetryPolicy(new DefaultRetryPolicy( 60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); mStringRequest.setShouldCache(true); // dialog.show(); SingletonRequestQueue.getInstance(context).addToRequestQueue(mStringRequest); }