2012-08-29 347 views
0

我想使用下面提到的代碼從谷歌驅動器下載文件。 我已經成功地測試了插入文件,刪除文件上傳文件等其他方法,但是當試圖下載文件時,我在下面的代碼中的HttpResponse response = request.execute()處收到401授權錯誤。谷歌驅動器文件下載

private static synchronized InputStream downloadFile(Drive service, File file) throws IOException 
    { 
     //File file = service.files().get(fileId).execute(); 
     String fileURL = file.getDownloadUrl(); 
     GenericUrl genericUrl = new GenericUrl(fileURL); 
     if (fileURL != null && fileURL.length() > 0) 
     { 
      try { 

        HttpRequest request = service.getRequestFactory().buildGetRequest(genericUrl); 
        HttpResponse response = request.execute(); 
        InputStream inStream = response.getContent(); 

        //HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute(); 
        System.out.println("content "+ inStream); 
        return inStream; 
      } catch (IOException e) { 

       // An error occurred. 
       e.printStackTrace(); 
       System.out.println("downloadFile error :"+ e.getMessage()); 
       return null; 
      } 
     } else { 
        // The file doesn't have any content stored on Drive. 
        return null; 
     } 
    } 

我也曾嘗試使用異步執行,我仍然得到401錯誤

08-30 19:31:13.917: W/System.err(1585): com.google.api.client.http.HttpResponseException: 401 Unauthorized 
08-30 19:31:13.925: W/System.err(1585):  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:978) 
08-30 19:31:13.935: W/System.err(1585):  at com.rise.risedrive.RiseDriveActivity$DownloadFile.doInBackground(RiseDriveActivity.java:112) 
08-30 19:31:13.945: W/System.err(1585):  at com.rise.risedrive.RiseDriveActivity$DownloadFile.doInBackground(RiseDriveActivity.java:1) 
08-30 19:31:13.955: W/System.err(1585):  at android.os.AsyncTask$2.call(AsyncTask.java:185) 
08-30 19:31:13.955: W/System.err(1585):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
08-30 19:31:13.965: W/System.err(1585):  at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
08-30 19:31:13.965: W/System.err(1585):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
08-30 19:31:13.975: W/System.err(1585):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
08-30 19:31:13.975: W/System.err(1585):  at java.lang.Thread.run(Thread.java:1019) 
08-30 19:31:32.250: W/jdwp(1585): Debugger is telling the VM to exit with code=1 
08-30 19:31:32.250: I/dalvikvm(1585): GC lifetime allocation: 2603 bytes 

我試圖調試它,但不能 幫我提前

解決這個

謝謝

+0

你能打印錯誤信息嗎?你可以找到更多關於如何從這個[頁面](https://developers.google.com/drive/handle-errors#catching_exceptions_with_client_libraries)發現錯誤的信息。憑據可能已過期,或者用戶可能已撤銷對您的應用程序的訪問權限。 – Alain

回答

0

你的代碼中沒有設置授權標頭。

你需要像

setRequestProperty("Authorization", "OAuth " + "***ACCESS_TOKEN***"); 

對於任何401/403錯誤,這是值得讓你請求的OAuth園地https://developers.google.com/oauthplayground/工作,所以你必須要在其上構建應用程序基準。

+0

'service.getRequestFactory()。buildGetRequest()'應該在內部做到這一點。 – devconsole