2013-07-09 66 views
22

我能够设置验证头正常HTTPURLConnection请求是这样的:如何设置(OAuth凭证)认证头在Android OKHTTPClient请求

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

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

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

在此先感谢任何指针。

+0

嗨,你有没有解决? – CeccoCQ

回答

17

如果使用当前版本(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年5月23日

新的请求和响应类型,每个都有自己的建设者。还有一个RequestBody类来将请求主体写入网络,还有一个ResponseBody从网络读取响应主体。 独立的Headers类提供对HTTP头的完全访问。

-1

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

这是错误的。它添加了BASIC身份验证而不是OAuth令牌 – checklist