I am trying to connect to a django server from my android application. I am trying to access my api, making a POST
request with volly. Everything is set. All th
i solved it my self... This code will get you an auth-token, with the username and password you provide, and then that token will be put in the header to get data from the server...
public void vollyRequestGetAuthToken()
{
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST , "https://example.com/get-auth-token/", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, "RESPONSE: " + response, Toast.LENGTH_SHORT ).show();
System.out.println("RESPONSE: >>> " + response + "<<<");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_SHORT ).show();
}
}) {
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username","*****");
params.put("password","*****");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Authorization",
String.format("Basic %s", Base64.encodeToString(
String.format("%s:%s", "<username>", "<password>").getBytes(), Base64.DEFAULT)));
params.put("username" , "*****" );
params.put("password" , "*****" );
return params;
}
};
queue.add(request);
}
and now when you have the auth-token, use the following code to send auth-token to get data
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token <token>");
return headers;
}
This is caused when the request is declined/blocked from the API End Point. The reason could be a malformed request for that,