我正在使用Postman来通过URL打服务器GET呼叫。并在postman的标头部分中添加以下标头,以便在postman中运行时可以正常工作并在正文中发送数据,但在Android中使用Retrofit时不会出现401错误。
X-APIClient: {"apiClientId":"testing-account-cli","apiToken":"$2y$10$C/quaRQUsrWa30hjQJuckOXbW9kIZ.W3G1TlLMYg6lr/XDUes7SM."}
X-Header-Request: {"deviceId":"ffffffff-daac-6513-4eca-0c41298e00df"}
它可以在邮递员上使用。但是在具有Retrofit的Android中,它无法正常工作401错误。
1)
@GET("user-list")
Call<User> getUsers(@HeaderMap Map<String, String> headers);
2)
public static Map<String,String> addCustomHeaders()
{
headers = new HashMap<>();
headers.put("X-APIClient",
"\"apiClientId\":\"testing-account-cli\",\"apiToken\":\"$2y$10$C/quaRQUsrWa30hjQJuckOXbW9kIZ.W3G1TlLMYg6lr/XDUes7SM.");
headers.put("X-Header-Request", "\"deviceId\":\"ffffffff-daac-6513-4eca-0c41298e00df")
;
return headers;
}
3)使用下面的方法调用GET总是失败
Call<User> call = api.getUsers(RetrofitClient.addCustomHeaders());
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Log.i(TAG, "GET User Success." + response.body().toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.i(TAG, "GET Failed Users." + t.getMessage());
}
});
请帮助解决问题。由于它始终会抛出401,其中包含身份验证错误和授权错误。
答案 0 :(得分:2)
在下面尝试功能,我分离了标题。
public static Map<String,String> addCustomHeaders()
{
HashMap<String, String> headers = new HashMap<>();
headers.put("apiClientId" ,"testing-account-cli");
headers.put("apiToken", "$2y$10$C/quaRQUsrWa30hjQJuckOXbW9kIZ.W3G1TlLMYg6lr/XDUes7SM.");
headers.put("deviceId","ffffffff-daac-6513-4eca-0c41298e00df");
return headers;
}
答案 1 :(得分:0)
对标题使用拦截器
public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.header("apiClientId", "testing-account-cli")
.header("apiToken","$2y$10$C/quaRQUsrWa30hjQJuckOXbW9kIZ.W3G1TlLMYg6lr/XDUes7SM.")
.header("deviceId","ffffffff-daac-6513-4eca-0c41298e00df")
.build()
Response response = chain.proceed(request);
return response;
}
//将此类添加到改造类中,例如
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new HeaderInterceptor())