在get header()volley中添加带有Authorization标头的自定义标头时,没有获得成功响应

时间:2015-07-18 14:57:17

标签: android url authorization android-volley

我已经提到了这个 Example,我收到了无效的令牌,因此我的身份验证标头工作正常,但自定义标头出错了。

自定义截击请求

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

添加自定义和授权标题

@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;

}

}

2 个答案:

答案 0 :(得分:2)

您使用的是正确的方法。你肯定需要覆盖getHeaders()。我猜你的问题就在这里:

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

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

答案 1 :(得分:0)

getHeaders()方法在提出请求时使用了空格和符号(引号),我纠正了它们并且对我来说很好。