如何从Django服务器获取Token并使用Volley

时间:2018-03-13 11:19:30

标签: authentication android-volley

我正在使用Django Rest Api作为我的Android应用程序的后端。我需要向服务器发送用户名和密码才能获得Token。这个我需要发送的令牌所有进一步的Api请求的标题。我在android中使用进行网络呼叫。如何发送UsernamePassword来获取令牌? 如何在Volley Header中发送该令牌?

1 个答案:

答案 0 :(得分:0)

首先使用用户名和密码发出请求以检索身份验证令牌:

JSONObject postparams = new JSONObject();
postparams.put("username","the_username")
postparams.put("password","the_password")

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
        "/url/to/obtain/token/end/point", postparams,
        new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                /** Retrieve the token from the response **/
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });

获得令牌后,您可以在所有后续API请求中的Authorization HTTP标头中传递令牌:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
        "/url/to/some/api/end/point", null,
        new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
              //Success Callback
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        })

{

    /** Pass the token in the Authorization header **/
    @Override
    public Map<string, string=""> getHeaders() throws AuthFailureError {
        HashMap<string, string=""> headers = new HashMap<string, string="">();
        headers.put("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b");
        return headers;
    }
};