使用Volley Android

时间:2016-09-25 19:12:47

标签: android laravel android-volley

我想发送一个请求并从它的cookie中获取XSRF-TOKEN,当我将POST发送到寄存器时,我想把它放入标题中。其实我想做点什么:access laravel app from android app with csrf token

我正在使用StringRequest发送这样的请求:

private void registerUser(final String name, final String email,
                          final String password,final String confirm) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    pDialog.setMessage("Registering ...");
    showDialog();

    final StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            datares = response;

            Log.d("REGISTER RESPONSE", "Register Response: " + response.toString());

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getActivity().getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);
            params.put("password-confirm",confirm);

            return params;
        }

    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

AppController.java

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

你知道我怎么能用Volley做到这一点?

1 个答案:

答案 0 :(得分:2)

这是一个迟到的答案。无论如何,如果有人偶然发现这里寻找任何答案,我会在这里添加其中一种方式:)

您可以使用csrf_exempt。它将免除CSRF考虑的观点。我不确定这是否是一个重大的安全风险,但它确实有效。

from django.views.decorators.csrf import csrf_exempt

# Create your views here.
from django.http import HttpResponse

@csrf_exempt
def homePageView(request):
    data = request.POST.get('data')
    return HttpResponse(data)