我想使用volley来构建具有身份验证的http连接。在this answer之后我添加了细分
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
在匿名内部班StringRequest
中,它看起来像:
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
//the segment below is what I add
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
String creds = String.format("%s:%s","USERNAME","PASSWORD");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
params.put("Authorization", auth);
return params;
}
//the segment above is what I add
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
但是,IDE提示getHeaders()
不会覆盖其超类。
为什么?我发现StringRequest扩展了类Request<String>
,而后者确实有一个名为getHeaders()
的方法。
答案 0 :(得分:2)
您在public Map<String, String> getHeaders()
的新实例中覆盖Response.Listener<String>
而不是Request<String>
而Response.Listener<String>
没有此类方法(仅onResponse(String)
)。