我可以像这样在普通 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/