2013-07-09 67 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