2013-03-06 72 views
3

我想使用Java Jersey而不是Google客戶端庫來訪問Google File API,但我一直得到返回「401 Unauthorized」的響應狀態。在撥打電話之前,我使用Oauth獲得了來自Google的訪問令牌:如何使用Jersey調用Google Drive REST API?

public static String getGoogleFileResource(final String fileId, 
     final String accessToken) { 
    //projection 

    ClientConfig cc = new DefaultClientConfig(); 
    cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); 
    Client client = Client.create(cc); 

    String url = String 
      .format("https://www.googleapis.com/drive/v2/files/%s?fields=downloadUrl&key=%s", 
        fileId, GoogleClientConstants.GOOGLE_api_key); 
    WebResource webResource = client.resource(url); 

    String response = webResource 
      .accept(MediaType.APPLICATION_JSON_TYPE, 
        MediaType.APPLICATION_XML_TYPE) 
      .header("Authorization", "Bearer " + accessToken) 
      .get(String.class); 

    logger.info("Authorization - " + "Bearer " + accessToken); 
    logger.info(" reponse " + response); 
    return response; 
} 

我在做什麼錯?

回答

0

原來,您需要將訪問令牌添加到http請求標頭。

在谷歌開發者指南:「上傳文件」

https://developers.google.com/drive/manage-uploads

您需要發送POST請求是這樣的:

POST /upload/drive/v2/files?uploadType=media HTTP/1.1 
Host: www.googleapis.com 
Content-Type: image/jpeg 
Content-Length: number_of_bytes_in_JPEG_file 
Authorization: your_auth_token 

JPEG data 

需要注意的是在標題,你需要把a your_auth_token