0

我正在尝试使用 JsonObjectRequest 发送用户名和密码作为基本授权。我尝试过覆盖getHeaders()方法,但它没有用。这是我的代码:

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));
    }
}

我使用时出错Base64.NO_WRAP

com.android.volley.AuthFailureError

当我使用Base64.DEFAULT

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

注意:此网络服务正在使用 Google Postman 工具。

4

1 回答 1

-3

检查我的答案,它对我来说工作正常。

检查这个

于 2017-01-24T11:28:40.887 回答