java - 如何在 Android OKHTTPClient 请求上设置(OAuth token )授权 header

标签 java android oauth httpurlconnection

我可以像这样在普通 HTTPURLConnection 请求上设置 Auth header :

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

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

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

提前感谢您的任何指点。

最佳答案

如果您使用当前版本(2.0.0),您可以在请求中添加 header :

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

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.

关于java - 如何在 Android OKHTTPClient 请求上设置(OAuth token )授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556594/

相关文章:

oauth - 基本身份验证或 Oauth 的 NTLM 代理转换器

java - Android、AccountManager 和 OAuth

java - 如何处理悬停在不同元素上并仅通过 css 更改不同元素的图像

Java,Play2.0 ,')' 预期但 '=' 找到 Play

java - 获取<xs :schema attributeFormDefault ="unqualified" elementFormDefault ="qualified" > in wsdl

java - Android Widget 未出现在 Widget 列表中

for 循环中的 Java 三维数组

android - 没有 singleLine 选项的 EditText 的 actionDone

android - 如何从设备上的命令行卸载 android 应用程序

ruby-on-rails - Mendeley 自定义 OAuth 策略