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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17556594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:18:21  来源:igfitidea点击:

How to set the (OAuth token) Authorization Header on an Android OKHTTPClient request

javaandroidoauthhttpurlconnection

提问by Alfie Hanssen

I'm able to set the Auth Header on normal HTTPURLConnectionrequests like this:

我可以在HTTPURLConnection像这样的正常请求上设置 Auth 标头:

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

This is standard for HttpURLConnection. In the above code snippet this.clientis an instance of Square's OkHTTPClient(here).

这是 HttpURLConnection 的标准。在上面的代码片段中this.client是 Square 的一个实例OkHTTPClient这里)。

I'm wondering if there is an OkHTTP-specific way of setting the Auth Header? I see the OkAuthenticatorclass but am not clear on how exactly to use it / it looks like it only handles authentication challenges.

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

Thanks in advance for any pointers.

在此先感谢您的指点。

回答by pt2121

If you use the current version (2.0.0), you can add a header to a request:

如果您使用当前版本 (2.0.0),则可以向请求添加标头:

Request request = new Request.Builder()
            .url("https://api.yourapi...")
            .header("ApiKey", "xxxxxxxx")
            .build();

Instead of using:

而不是使用:

connection.setRequestMethod("GET");    
connection.setRequestProperty("ApiKey", "xxxxxxxx");

However, for the older versions (1.x), I think the implementation you use is the only way to achieve that. As their changelogmentions:

但是,对于旧版本 (1.x),我认为您使用的实现是实现这一目标的唯一方法。正如他们的更新日志所提到的:

Version 2.0.0-RC1 2014-05-23

版本 2.0.0-RC1 2014-05-23

New Request and Response types, each with their own builder. There's also a RequestBody class to write the request body to the network and a ResponseBody to read the response body from the network. The standalone Headers class offers full access to the HTTP headers.

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

回答by Laurent Russier

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

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