トラッキング コード

1/17/2015

How to add Volley Request with parameter of POST and Headers

If need to add parameter of POST and Headers, you need to read the following source code.
There are getHeaders() and getParams() in Request class which is super class of StringRequest class.
     /**
     * Returns a list of extra HTTP headers to go along with this request. Can
     * throw {@link AuthFailureError} as authentication may be required to
     * provide these values.
     * @throws AuthFailureError In the event of auth failure
     */
    public Map<String, String> getHeaders() throws AuthFailureError {
        return Collections.emptyMap();
    }

     /**
     * Returns a Map of parameters to be used for a POST or PUT request.  Can throw
     * {@link AuthFailureError} as authentication may be required to provide these values.
     *
     * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
     *
     * @throws AuthFailureError in the event of auth failure
     */
    protected Map<String, String> getParams() throws AuthFailureError {
        return null;
    }

We can add parameter when do override getHeaders() and getParams() method.The following source is sample.


    /**
     * Request(StringRequest) with params
     *
     * @param url      request url
     * @param listener listener for Response or Error
     * @param params   value of setting Http Params
     * @param headers  value of setting Http headers
     */
    public void get(String url, final ResponseListener listener, final Map<String, String> params
            , final Map<String, String> headers) {
 
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        listener.onResponse(s);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        listener.onErrorResponse(volleyError);
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
 
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return headers;
            }
        };
 
        mRequestQueue.add(request);
    }

No comments:

Post a Comment