如何在Android OKHTTPClient请求中设置(OAuth token)授权头Authorization Header

22

我可以在普通的HTTPURLConnection请求中设置身份验证标头,如下所示:

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特定的方法来设置身份验证标头?我看到了OkAuthenticator类,但不清楚如何使用它或者它似乎只处理身份验证挑战。

感谢您提前提供任何指针。

2个回答

17
如果您使用当前版本(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),我认为你使用的实现方法是实现该功能的唯一方式。因为在他们的变更日志中提到:

Version 2.0.0-RC1 2014-05-23

新的请求和响应类型,每个类型都有自己的构建器。还有一个RequestBody类用于将请求主体写入网络,以及一个ResponseBody用于从网络读取响应主体。独立的Headers类提供了完全访问HTTP标头的功能。


-1

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/com/squareup/okhttp/recipes/Authenticate.java

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.
  }
});

1
这是错误的。它添加了基本身份验证而不是OAuth令牌。 - checklist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接