在截击请求中添加自定义标头

时间:2015-10-10 12:31:27

标签: android android-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的标题?

4 个答案:

答案 0 :(得分:24)

在请求中覆盖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;
        }
    };

答案 1 :(得分:0)

你可以编写一个扩展请求类。(覆盖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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

<块引用>

这是一个示例 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);
    }
}