如何在 Android OKHTTPClient 请求上设置(OAuth 令牌)授权标头

2022-09-02 01:50:14

我能够在正常请求上设置身份验证标头,如下所示:HTTPURLConnection

URL url = new URL(source);  
HttpURLConnection connection = this.client.open(url);  
connection.setRequestMethod("GET");  
connection.setRequestProperty("Authorization", "Bearer " + token);  

这是HttpURLConnection的标准配置。在上面的代码片段中,是Square的一个实例(这里)。this.clientOkHTTPClient

我想知道是否有设置身份验证标头的特定方法?我看到了该类,但不清楚如何确切地使用它/看起来它只处理身份验证挑战。OkHTTPOkAuthenticator

提前感谢您的任何指点。


答案 1

如果您使用当前版本 (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 标头的完全访问。


答案 2

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

推荐