当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Volley JsonObjectRequest with Basic Auth headers didn't work

问题描述:

I'm trying to send username and password as basic authorization with JsonObjectRequest. I've tried to Override getHeaders() method but it didn't work. Here is my code:

public class NewPostRequest extends JsonObjectRequest {

public NewPostRequest(JSONObject requestBody) {

super(Method.POST, APIConstants.CREATE_POST_URL, requestBody, new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {

try {

long postId = response.getLong("id");

NewPostResponse newPostResponse = new NewPostResponse(postId);

EventBus.getDefault().post(newPostResponse);

} catch (JSONException e) {

e.printStackTrace();

EventBus.getDefault().post(new NewPostResponse(-1));

}

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

EventBus.getDefault().post(new NewPostResponse(-1));

}

});

}

@Override

public Map<String, String> getHeaders() throws AuthFailureError {

Map<String, String> headers = new HashMap<>();

String credentials = "****:***********************";

String auth = "Basic "

+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

headers.put("Content-Type", "application/json; charset=utf-8");

headers.put("Authorization", auth);

return headers;

}

@Override

protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {

JSONObject jsonObject = null;

try {

String data = new String(response.data,

HttpHeaderParser.parseCharset(response.headers));

jsonObject = new JSONObject(data);

} catch (UnsupportedEncodingException | JSONException e) {

e.printStackTrace();

}

return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));

}

}

Error when i used Base64.NO_WRAP:

com.android.volley.AuthFailureError

And when i used Base64.DEFAULT:

java.lang.IllegalArgumentException: Unexpected char 0x0a at 46 in header value: Basic *************************

Note: This web service is working on Google Postman tool.

网友答案:

Check my answer its working fine for me.

Check this one

分享给朋友:
您可能感兴趣的文章:
随机阅读: