2014-01-19 110 views
2

我想要訪問Google AnalyticsManagement API來創建視圖並且已經通過OAuth Playground使用作爲analytics.edit的作用域獲取訪問令牌。令牌測試有效。但是,我一直在運行我的代碼使用HttpUrlConnection發送訪問令牌(401錯誤)使用HttpUrlConnection

我的代碼如下得到一個401錯誤,編碼的語言在Java

//where urlStr is https://www.googleapis.com/analytics/v3/management/accounts/accountId/webproperties/webPropertyId/profiles with relevant account id, web propertyId and inclusive of request body 

String authEncoded = Base64.encodeBytes(accessToken.getBytes()); 

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestMethod("POST"); 
connection.setDoOutput(true); 
connection.setRequestProperty("Authorization", "Basic " + authEncoded); 
OutputStream output = connection.getOutputStream(); 


output.write(query.getBytes("UTF-8")); 


InputStream response = connection.getInputStream(); 

上面的代碼在IOException的嘗試捕捉包圍。然而,從輸入流的響應總是給我一個錯誤

「java.io.IOException異常:服務器返回的HTTP響應代碼:401網址:」

有什麼我錯過了或有任何其他方式來設置訪問令牌發送到谷歌API?

+0

AFAIK基本驗證是不是這樣做的方法。也許http://stackoverflow.com/questions/11068892/oauth-2-0-authorization-header幫助或閱讀一些谷歌文檔。 – hgoebl

回答

1

使用oauth.io/android,您可以直接建立與相關信息您的要求其提供:

data.http(urlStr, new OAuthRequest() { 
    private URL url; 
    private HttpURLConnection con; 

    @Override 
    public void onSetURL(String _url) { 
     try { 
      url = new URL(_url); 
      con = (HttpURLConnection) url.openConnection(); 
     } catch (Exception e) { e.printStackTrace(); } 
    } 

    @Override 
    public void onSetHeader(String header, String value) { 
     con.addRequestProperty(header, value); 
    } 

    @Override 
    public void onReady() { 
     InputStream response = con.getInputStream(); 
     // ... 
    } 
}); 

這是一個完整的例子:https://github.com/oauth-io/oauth-android/blob/master/example/MainActivity.java

相關問題