请求被调用两次,我收到401错误,这是服务器身份验证错误,就像令牌无效(我已经检查过并且令牌有效):
我试过了:
public void getUserFriends(final API.OnAPIResponse listener) {
FriendsRequest request = FriendsRequest.newInstance(listener);
//added this to see if it stopped being called twice
request.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance().addToRequestQueue(request);
}
private static class FriendsRequest extends StringRequest {
public static FriendsRequest newInstance(final API.OnAPIResponse listener) {
String serviceURL = API.API_URL + FRIENDS_PATH;
return new FriendsRequest(Request.Method.GET, serviceURL, new Response.Listener < String > () {
@Override
public void onResponse(String response) {
APIResponse apiResponse = null;
if (listener != null) {
listener.onResponse(apiResponse);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
APIResponse apiResponse = getErrorResponse(error);
if (listener != null) {
listener.onResponse(apiResponse);
}
}
});
}
public FriendsRequest(int method, String url, Response.Listener < String > listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
public FriendsRequest(String url, Response.Listener < String > listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
@Override
public Map < String, String > getHeaders() throws AuthFailureError {
HashMap < String, String > headers = new API().getTokenHeader();
headers.put("Content-Type", "application/json; charset=utf-8");
Log.d("Network", headers.toString());
return headers;
}
}
我确实设法向该API发出请求,但并不需要令牌标头。
更新:我还在努力;使用EasyVolley,我得到了同样的错误:
EasyVolley.withGlobalQueue()
.load(API_URL + FRIENDS_PATH)
.addHeader("token", TokenGenerator.getToken())
.addHeader("Content-Type", "application/json; charset=utf-8")
.asJsonObject()
.setSubscriber(mainActivity)
.setCallback(new ASFRequestListener<JsonObject>() {
@Override
public void onSuccess(JsonObject response) {
Log.d("response", response.toString());
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
}
})
.start();
得到同样的错误,但至少它被调用一次:
更新:使用OkHttp测试,不知道还有什么要尝试,我已多次检查,令牌在RESTClient中运行。
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new
okhttp3.Request.Builder()
.header("token", TokenGenerator.getToken())
.url(API_URL + FRIENDS_PATH)
.build();
// Get a handler that can be used to post to the main thread
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
response.headers();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
}
});