I need to call a REST API that simply updates the value of a field in the database. To do this, I use the following Volley request, but it return an Unexpected response code 401 (unauthorized), it seems as if the headers for OAuth2 authorization get ignored. I checked the access token value and it is there correctly. What's my mistake?
private void sendRegistrationTokenToServer(final String token) {
// user ID taken from SharedPreferences
final String id = Integer.toString(SharedPrefManager.getInstance(this).getUserId());
StringRequest stringRequest = new StringRequest
(
Request.Method.PUT,
Constants.URL_GCM_TOKEN+"/"+ Utils.base64Encode(id),
new Response.Listener<String>()
{
@Override
public void onResponse(String s)
{
Intent registrationComplete = new Intent(REGISTRATION_TOKEN_SENT);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError volleyError)
{
Toast.makeText(getBaseContext(), "Unexpected error occurred when saving the GCM token for push notifications", Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("gcm_token", token);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
String bearer = "Bearer ".concat(SharedPrefManager.getInstance(getBaseContext()).getUserAccessToken());
headers.put("Authorization", bearer);
return headers;
}
};
App.getInstance().addToRequestQueue(stringRequest);
}
I answer myself, in case someone needed to know the solution :) For some motivation, the server policy removes the Authorization header, so I had to provide a different custom header, named X-Authorization-Copy , with the same values as the Authorization one (" Bearer "), and I had to modify the server code in order to manage the case where the Authorization header is not found in the request. So the server checks if the other custom X-Authorization-Copy header is present and it takes authorization data from it. Further, the Content-Type header must be x-www-form-urlencoded, instead of application/json, otherwise it will give an error. Now it works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.