在 get header() volley 中使用 Authorization header 添加自定义 headers 时未获得成功响应

not getting success response when adding custom headers with Authorization header in get header() volley

我已经提到了这个 Example ,我收到无效令牌作为响应,因此我的身份验证 header 工作正常,但自定义 headers.

有问题

自定义排球请求

 public CustomRequest(String url, Map<String, String> params,
                     Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.listener = reponseListener;
    this.params = params;


}

public CustomRequest(int method, String url, Map<String, String> params,
                     Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

public CustomRequest(int method, String url, Map<String, String> params,
                     Listener<JSONObject> reponseListener, ErrorListener errorListener, Boolean head, String tok, String id) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    headadd = head;
    this.id = id;
    this.token = tok;

}

protected Map<String, String> getParams()
        throws com.android.volley.AuthFailureError {

    return params;
}

adding custom and Authorization header

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> head = new HashMap<>();


    head.put(
            "Authorization",
            String.format("Basic %s", Base64.encodeToString(
                    String.format("%s:%s", "xxxxxxx", "xxxxxxx").getBytes(), Base64.DEFAULT)));
    if (headadd) {
        head.put("token", token);
        head.put("client_id", id);
    }
    return head;
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

@Override
public RetryPolicy getRetryPolicy() {
    RetryPolicy retryPolicy = new DefaultRetryPolicy(
            0,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
    );
    return retryPolicy;

}

}

您使用的方法正确。您肯定需要覆盖 getHeaders()。我的猜测是您的问题出在此处:

String.format("Basic %s", Base64.encodeToString(
String.format("%s:%s", "uictester", "?f!T!ziX}.,(").getBytes(), Base64.DEFAULT)));

也许您需要将其转换为 UTF-8? 否则,您可以通过构造函数传入 headers 映射,看看是否有帮助。它可能也比 hard-coding 那样更灵活。 看起来你实际上是在 CustomRequest 中传递参数而不是使用它们?

getHeaders() 方法在发出请求时使用空格和符号(引号),我更正了它们并且对我来说工作正常。