带有基本身份验证标头的 Volley JsonObjectRequest 不起作用

问题描述 投票:0回答:2

我正在尝试使用 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 工具上运行。

android web-services android-volley basic-authentication jsonobjectrequest
2个回答
0
投票

你是如何解决这个错误的?


-4
投票

检查我的答案,它对我来说效果很好。

检查这个

© www.soinside.com 2019 - 2024. All rights reserved.