【问题标题】:How to set the (OAuth token) Authorization Header on an Android OKHTTPClient request如何在 Android OKHTTPClient 请求上设置(OAuth 令牌)授权标头
【发布时间】:2013-07-07 13:17:17
【问题描述】:

我可以在正常的HTTPURLConnection 请求上设置 Auth Header,如下所示:

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

这是 HttpURLConnection 的标准。在上面的代码中,sn -p this.client 是 Square 的 OkHTTPClient (here) 的一个实例。

我想知道是否有 OkHTTP 特定的方式来设置 Auth Header?我看到了 OkAuthenticator 类,但不清楚如何准确使用它/看起来它只处理身份验证挑战。

提前感谢您的任何指点。

【问题讨论】:

    标签: java android oauth httpurlconnection


    【解决方案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),我认为您使用的实现是实现这一目标的唯一方法。正如their changelog 提到的:

    版本 2.0.0-RC1 2014-05-23

    新的请求和响应类型,每个类型都有自己的构建器。还有一个 RequestBody 类用于将请求正文写入网络,还有一个 ResponseBody 用于从网络读取响应正文。 独立的 Headers 类提供对 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.
        }
      });
      

      【讨论】:

      • 这是错误的。它添加了 BASIC 身份验证而不是 OAuth 令牌
      猜你喜欢
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 2021-03-03
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2011-11-16
      相关资源
      最近更新 更多