Java 如何在Android OKHTTPClient请求上设置(OAuth令牌)授权头
我可以在正常的Java 如何在Android OKHTTPClient请求上设置(OAuth令牌)授权头,java,android,oauth,httpurlconnection,Java,Android,Oauth,Httpurlconnection,我可以在正常的HTTPURLConnection请求上设置Auth头,如下所示: URL url = new URL(source); HttpURLConnection connection = this.client.open(url); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Bearer " + token); 这是HttpURLConnect
HTTPURLConnection
请求上设置Auth头,如下所示:
URL url = new URL(source);
HttpURLConnection connection = this.client.open(url);
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + token);
这是HttpURLConnection的标准配置。在上面的代码片段中,this.client是Square的OkHTTPClient
()的一个实例
我想知道是否有一种OkHTTP
特定的方式来设置Auth头?我看到了OkAuthenticator
类,但不清楚如何准确地使用它/它看起来只处理身份验证挑战
提前感谢您的指点 如果使用当前版本(2.0.0),则可以向请求添加标题:
Request request = new Request.Builder()
.url("https://api.yourapi...")
.header("ApiKey", "xxxxxxxx")
.build();
而不是使用:
connection.setRequestMethod("GET");
connection.setRequestProperty("ApiKey", "xxxxxxxx");
但是,对于旧版本(1.x),我认为您使用的实现是实现这一点的唯一方法。如前所述:
版本2.0.0-RC1 2014-05-23
新的请求和响应类型,每个类型都有自己的生成器。还有一个RequestBody类将请求主体写入网络,还有一个ResponseBody从网络读取响应主体独立标头类提供对HTTP标头的完全访问。
这是错误的。它添加了一个基本的身份验证,而不是OAuth令牌
client.setAuthenticator(new Authenticator() {
@Override public Request authenticate(Proxy proxy, Response response) {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
@Override public Request authenticateProxy(Proxy proxy, Response response) {
return null; // Null indicates no attempt to authenticate.
}
});