我正在开发一个Android项目,试图与Retrofit一起使用摘要认证。我惊讶于Retrofit不支持它(或更准确地说,OkHttp不支持它),但我想没有抱怨的必要。
我在这里浏览了很多帖子,似乎正确的解决方案是将原生支持摘要认证的Apache HttpClient与Retrofit集成。这需要用retrofit.client.Client实现来包装HttpClient。然后必须解析和构建 retrofit 的传入值,并将其打包成新的 HttpClient 响应,然后发送回 Retrofit 进行正常处理。感谢 Jason Tu 和他的示例:https://gist.github.com/nucleartide/24628083decb65a4562c
问题是,它不起作用。每次都会得到401未授权错误,而我不清楚原因。这是我的Client实现:
public class AuthClientRedirector implements Client {
private final CloseableHttpClient delegate;
public AuthClientRedirector(String user, String pass, String hostname, String scope) {
Credentials credentials = new UsernamePasswordCredentials(user, pass);
AuthScope authScope = new AuthScope(hostname, 443, scope);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(authScope, credentials);
delegate = HttpClientBuilder.create()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
@Override
public Response execute(Request request) {
//
// We're getting a Retrofit request, but we need to execute an Apache
// HttpUriRequest instead. Use the info in the Retrofit request to create
// an Apache HttpUriRequest.
//
String method = request.getMethod();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (request.getBody() != null) {
try {
request.getBody().writeTo(bos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String body = new String(bos.toByteArray());
HttpUriRequest wrappedRequest;
switch (method) {
case "GET":
wrappedRequest = new HttpGet(request.getUrl());
break;
case "POST":
wrappedRequest = new HttpPost(request.getUrl());
wrappedRequest.addHeader("Content-Type", "application/xml");
try {
((HttpPost) wrappedRequest).setEntity(new StringEntity(body));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case "PUT":
wrappedRequest = new HttpPut(request.getUrl());
wrappedRequest.addHeader("Content-Type", "application/xml");
try {
((HttpPut) wrappedRequest).setEntity(new StringEntity(body));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case "DELETE":
wrappedRequest = new HttpDelete(request.getUrl());
break;
default:
throw new AssertionError("HTTP operation not supported.");
}
CloseableHttpResponse apacheResponse = null;
try {
apacheResponse = delegate.execute(wrappedRequest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(apacheResponse!=null){
// Perform the HTTP request.
CloseableHttpResponse response = null;
try {
response = delegate.execute(wrappedRequest);
// Return a Retrofit response.
List<Header> retrofitHeaders = toRetrofitHeaders(
response.getAllHeaders());
TypedByteArray responseBody;
if (response.getEntity() != null) {
responseBody = new TypedByteArray("",
toByteArray(response.getEntity()));
} else {
responseBody = new TypedByteArray("",
new byte[0]);
}
System.out.println("this is the response");
System.out.println(new String(responseBody.getBytes()));
return new retrofit.client.Response(request.getUrl(),
response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase(), retrofitHeaders,
responseBody);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//failed to return a new retrofit Client
return null;
}
private List<Header> toRetrofitHeaders(org.apache.http.Header[] headers) {
List<Header> retrofitHeaders = new ArrayList<>();
for (org.apache.http.Header header : headers) {
retrofitHeaders.add(new Header(header.getName(), header.getValue()));
}
return retrofitHeaders;
}
private byte[] toByteArray(HttpEntity entity) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.writeTo(bos);
return bos.toByteArray();
}
}
我的改装配置看起来像这样:
public final RestAdapter configureService(){
AuthClientRedirector digestAuthMgr = new AuthClientRedirector(username,password,"myhostname","public");
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint("http://myhostname:8003/endpoint")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(digestAuthMgr);
return builder.build();
}
我很困惑,为什么服务器一直返回401错误。我已经检查了响应生成过程,看起来很干净,所以我认为我可能漏掉了一些基本的东西。凭据是正确的,我已经在应用程序外验证过它们。有人之前走过这条路吗?