我有一个形式的 curl curl -v -u username:password -H "Content-Type: application/json"........
无法破解如何让 -u
部分工作。尝试过多种选择,例如
Authenticator proxyAuthenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("username", "password");
return response.request().newBuilder()
.addHeader("Proxy-Authorization", credential)
.addHeader("Content-Type", "application/json")
.build();
}
};
和
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
RequestBody requestBody = new FormBody.Builder().add("username", "password").build();
Request request = original.newBuilder()
.addHeader("Content-Type", "application/json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
这两个都不起作用。即使将其发布为标题也无法使其正常工作。请大家帮忙!
最佳答案
按照这个解决了。
protected Authenticator getBasicAuth(final String username, final String password) {
return new Authenticator() {
private int mCounter = 0;
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (mCounter++ > 0) {
return null;
} else {
String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Authorization", credential).build();
}
}
};
}
然后将其作为身份 validator 添加到我的客户端。
关于java - Curl 到 okhttp 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638803/