Volley StringRequest标头块参数

时间:2017-02-28 11:53:29

标签: android http android-volley

我的Volley代码曾经像这样正常工作:

StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        //parameters are declared above this part of the code
        return parameters;
    }
};

然后我从服务器端的php文件中得到了错误403。人们建议添加标题以供请求。所以我将我的代码更改为:

StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        //parameters are declared above this part of the code
        return parameters;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError
    {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/form-data; charset=utf-8");
        return headers;
    }
};

添加标题后,我能够摆脱错误403,但现在Volley没有将我的参数传递给服务器。一切似乎都是空的。

我也尝试使用getBodyContentType()而不是GetHeaders(),但仍然会出现同样的问题。

编辑,整个代码:

public static void execute(final Request request, Context context){
    if(queue == null)
        queue = Volley.newRequestQueue(context);

    final Map<String, String> parameters = new HashMap<String, String>();
    for(int index = 0; index < request.getParameters().length; index++){
        parameters.put(request.getParameters()[index].getName(), request.getParameters()[index].getValue());
    }

    int method;
    switch (request.getRequestType()){
        case GET: method = Method.GET; break;
        case POST: method = Method.POST; break;
        default: method = Method.POST; break;
    }

    String URL = request.getURL();

    VolleyRequest newPostRequest = new VolleyRequest
            (com.android.volley.Request.Method.POST, URL, parameters, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    request.onResponse(response.toString());

                }
            }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println(error.getMessage());
                        // TODO Auto-generated method stub

                    }
                })
    {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> headers = new HashMap<String, String>();
                        headers.put("Content-Type", "aapplication/x-www-form-urlencoded; charset=UTF-8");
                        return headers;

                    }

                };

    queue.add(newPostRequest);
}

服务器端:

<?php
require_once 'connection.php';

$name = $_POST['name'];
$token = $_POST['token'];

if(strlen($name) < 4){
    $feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
    echo json_encode($feed);
    die;
}

$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
    $feed = array("Result" => "Failed", "Message" => "This name is already taken!");
    echo json_encode($feed);
    die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);

?>

2 个答案:

答案 0 :(得分:0)

按照这种方式。使用此自定义请求类。

public class VolleyRequest extends Request<JSONObject> {

    private Response.Listener<JSONObject> listener;
    private Map<String, String> params;

    public VolleyRequest(String url, Map<String, String> params,
                         Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public VolleyRequest(int method, String url, Map<String, String> params,
                         Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    }



    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}

并以这种方式实施 -

    Map<String, String> params = new HashMap<String, String>();
     params.put("param_1", "value_1");
     params.put("param_2", "value_2");

     VolleyRequest newPostRequest = new VolleyRequest
                    (Request.Method.POST, url, params, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(CLASS_NAME, " Response: " + response.toString());


                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // TODO Auto-generated method stub

                        }
                    }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/form-data; charset=utf-8");

                    return headers;

                }

            };

Volley.newRequestQueue(context.getApplicationContext()).add(newPostRequest);

Edit2:ServerSide代码:

require_once 'connection.php';

$name = $_POST['name'];
$token = $_POST['token'];

if(strlen($name) < 4){
    $feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
    echo json_encode($feed);
    die;
}

$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
    $feed = array("Result" => "Failed", "Message" => "This name is already taken!");
    echo json_encode($feed);
    die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);

答案 1 :(得分:0)

实际上,我的 Volley StringRequest 与您有类似的问题。
我需要将授权标头以及参数传递给服务器(以我的情况为CodeIgniter)

我将内容类型行从json更改为application / x-www-form-urlencoded; charset = UTF-8和瞧!有效

//Setting Headers
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                headers.put("Authorization-token", func.getAuthorizationToken(getActivity()));
                return headers;
            }

            //Adding parameters
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("user_id", "" + func.getSharedUserID(getActivity()));//Logged in user
                Log.e("Passed User ID: ", func.getSharedUserID(getActivity()));
                return params;
            }