【问题标题】:Add custom headers in volley request在凌空请求中添加自定义标头
【发布时间】:2015-10-10 12:31:27
【问题描述】:

我有一个 Volley 请求代码

RequestQueue queue = Volley.newRequestQueue(this);
String url =<My URL>;

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

如何在这个中设置一个名为 Authorization 的标头??

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    在请求中覆盖 getHeaders,例如:

     StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // Display the first 500 characters of the response string.
                        mTextView.setText("Response is: "+ response.substring(0,500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText("That didn't work!");
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> params =  super.getHeaders();
                if(params==null)params = new HashMap<>();
                params.put("Authorization","Your authorization");
                //..add other headers
                return params;
            }
        };
    

    【讨论】:

    • 如果你得到 VolleyError: java.lang.UnsupportedOperationException,删除 Map params = super.getHeaders(); if(params==null)params = new HashMap(); , 并添加 Map params = new HashMap();参考这个:stackoverflow.com/a/37344416/1371949
    【解决方案2】:

    这是一个示例 volley 请求,展示如何添加标头

    private void call_api(final String url){
    
        if(!this.isFinishing() && getApplicationContext() != null){
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    resultsTextView.setVisibility(View.INVISIBLE);
                    loader.setVisibility(View.VISIBLE);
                }
            });
    
            Log.e("APICALL", "\n token: " + url);
    
    
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.e("APICALL", "\n response: " + response);
                            if(!FinalActivity.this.isFinishing()){
                                try {
                                    JSONObject response_json_object = new JSONObject(response);
    
                                        JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
                                        final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
                                        final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
                                        last_results_type = k.getString("type");
                                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
    
                                                loader.setVisibility(View.INVISIBLE);
                                                resultsTextView.setText(result);
                                                resultsTextView.setVisibility(View.VISIBLE);
                                            }
                                        });
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
                                    finish();
                                }
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("APICALL", "\n error: " + error.getMessage());
                            Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }) {
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("apiUser", "user");
                    headers.put("apiKey", "key");
                    headers.put("Accept", "application/json");
                    //headers.put("Contenttype", "application/json");
                    return headers;
                }
    
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map = new HashMap<>();
                    map.put("location", "10.12 12.32");
                    return map;
                }
    
            };
            stringRequest.setShouldCache(false);
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    
            RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
            requestQueue.add(stringRequest);
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以写一个类 extends Request.(override getHeaders() 等等) 就像

      public abstract class AbsRequest<T> extends Request<T>{
      
          public AbsRequest(int method, String url, Response.ErrorListener listener) {
              this(method, url, null, listener);
          }
      
          public AbsRequest(int method, String url, Map<String, String> params, Response.ErrorListener listener) {
              this(method, url, params, null, listener);
          }
      
          public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, Response.ErrorListener listener) {
              this(method, url, params, head, null, listener);
          }
      
          public AbsRequest(int method, String url, Map<String, String> params, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
              this(method, url, params, null, head, bodyContentType, listener);
          }
      
          public AbsRequest(int method, String url, String body, Map<String, String> head, String bodyContentType, Response.ErrorListener listener) {
              this(method, url, null, body, head, bodyContentType, listener);
          }
      
          private AbsRequest(int method, String url, Map<String, String> params, String body, Map<String, String> head, String bodyContentType,  Response.ErrorListener listener) {
              super(method, url, listener);
          }
      }
      

      更多信息可以看https://github.com/Caij/CodeHub/blob/master/lib/src/main/java/com/caij/lib/volley/request/AbsRequest.java 使用方法可以看https://github.com/Caij/CodeHub/tree/master/app/src/main/java/com/caij/codehub/presenter/imp

      【讨论】:

        【解决方案4】:

        对 super.getHeaders() 的调用会引发 UnSupportedOperationException。 删除 super.getHeaders() 以摆脱它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-16
          • 2016-11-14
          • 2012-11-15
          • 1970-01-01
          相关资源
          最近更新 更多