SilverHoodCorp / gdata-java-client

Automatically exported from code.google.com/p/gdata-java-client
Apache License 2.0
0 stars 0 forks source link

Google Docs API : Unauthorized while downloading the excel document #386

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I  wanted  to  download  the  excel  document using Java Google Data API. I can 
see the list of excel document.But when I going to download the file always got 
the following exception:

Exception in thread "main" com.google.gdata.util.AuthenticationException: 
Unauthorized

<HTML>
<HEAD>
<TITLE> Unauthorized </TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

        at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
        at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
        at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
        at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
        at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
        at com.dashboard.googleapps.client.media.MediaService.getMediaResource(MediaService.java:234)
        at com.dashboard.googleapps.client.media.MediaService.getMedia(MediaService.java:276)
        at com.dashboard.googleapps.client.media.MediaService.getMedia(MediaService.java:302)
        at com.dashboard.googleapps.gui.AuthExample.downloadSpreadsheet(AuthExample.java:172)
        at com.dashboard.googleapps.gui.AuthExample.main(AuthExample.java:93) 

Here is my code for download the excel document.

public class AuthExample {

    private static DocsService docService = new DocsService("wise");

    public static void main(String[] args)throws Exception {
        String adminUser = "userId";
        String adminPassword = "password";
        String authToken = "authToken";
        String impersonatedUser = "";

        loginToDomain(adminUser, adminPassword, authToken);

        URL url = new URL("https://docs.google.com/feeds/default/private/full");
        DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);

        DocumentListEntry entry = feed.getEntries().get(0);

        for (DocumentListEntry entry1 : feed.getEntries()) {
            printDocumentEntry(entry1);
        }

        String title = entry.getTitle().getPlainText();
        System.out.println(title);

        String type = entry.getType();
        System.out.println(type);
        if (type.equals("document")) {
            String encodedAdminUser = URLEncoder.encode(adminUser);
            String resourceId = entry.getResourceId();
            String resourceIdNoPrefix = resourceId.substring(resourceId.indexOf(':') + 1);

            String downloadUrl =  "https://docs.google.com/feeds/download/documents/Export?xoauth_requestor=" + encodedAdminUser"&docId=" + resourceIdNoPrefix"&exportFormat=doc";

            downloadFile(downloadUrl, title + ".doc");
        } else if (type.equals("spreadsheet")) {
            String encodedAdminUser = URLEncoder.encode(adminUser);
            String resourceId = entry.getResourceId();
            String resourceIdNoPrefix = resourceId.substring(resourceId.indexOf(':') + 1);

            String downloadUrl = "https://spreadsheets.google.com/feeds/"
                    + "download/spreadsheets/Export?"
                    + "xoauth_requestor=" + encodedAdminUser
                    + "key=" + resourceIdNoPrefix + "&exportFormat=xls&gid=1";

            downloadSpreadsheet(resourceId, downloadUrl, "xls");
        }
    }

    private static void loginToDomain(String adminUser, String adminPassword, String authToken)
            throws OAuthException, AuthenticationException {
        String domain = adminUser.substring(adminUser.indexOf('@') + 1);

        GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
        oauthParameters.setOAuthConsumerKey(domain);
        oauthParameters.setOAuthConsumerSecret(authToken);
        oauthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
        oauthParameters.setScope("https://docs.google.com/feeds/ http://spreadsheets.google.com/feeds/ http://docs.googleusercontent.com/");

        docService.useSsl();
        docService.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
        docService.setUserCredentials(adminUser, adminPassword);
    }

    public static void downloadSpreadsheet(String resourceId, String filepath, String format)
            throws IOException, MalformedURLException, ServiceException {

        // Valid spreadsheet export formats
        HashMap SPREADSHEET_FORMATS = new HashMap();
        SPREADSHEET_FORMATS.put("xls", "4");
        SPREADSHEET_FORMATS.put("ods", "13");
        SPREADSHEET_FORMATS.put("pdf", "12");
        SPREADSHEET_FORMATS.put("csv", "5");
        SPREADSHEET_FORMATS.put("tsv", "23");
        SPREADSHEET_FORMATS.put("html", "102");

        String key = resourceId.substring(resourceId.lastIndexOf(':') + 1);

        String exportUrl = "https://spreadsheets.google.com/feeds/download/spreadsheets"
                + "/Export?key=" + key + "&fmcmd=" + SPREADSHEET_FORMATS.get(format);

        // If exporting to .csv or .tsv, add the gid parameter to specify which sheet to export
        if (format.equals("csv") || format.equals("tsv")) {
            exportUrl += "&gid=0";  // gid=0 will download only the first sheet
        }

        System.out.println("Exporting document from: " + exportUrl);

        MediaContent mc = new MediaContent();
        mc.setUri(exportUrl.toString());
        MediaSource ms = docService.getMedia(mc);

        InputStream inStream = null;
        FileOutputStream outStream = null;

        try {
            inStream = ms.getInputStream();
            outStream = new FileOutputStream(filepath);

            int c;
            while ((c = inStream.read()) != -1) {
                outStream.write(c);
            }
        } finally {
            if (inStream != null) {
                inStream.close();
            }

            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        }
    }

    public static void printDocumentEntry(DocumentListEntry doc) {
        if (doc.getType().equals("spreadsheet")) {
            String resourceId = doc.getResourceId();
            String docType = resourceId.substring(0, resourceId.lastIndexOf(':'));

            System.out.println("'" + doc.getTitle().getPlainText() + "' (" + docType + ")");
            System.out.println("  link to Google Docs: " + doc.getHtmlLink().getHref());
            System.out.println("  resource id: " + resourceId);

            // print the parent folder the document is in
            if (!doc.getFolders().isEmpty()) {
                System.out.println("  in folder: " + doc.getFolders());
            }

            // print the timestamp the document was last viewed
            DateTime lastViewed = doc.getLastViewed();
            if (lastViewed != null) {
                System.out.println("  last viewed: " + lastViewed.toString());
            }

            // print who made that modification
            LastModifiedBy lastModifiedBy = doc.getLastModifiedBy();
            if (lastModifiedBy != null) {
                System.out.println("  updated by: "
                        + lastModifiedBy.getName() + " - " + lastModifiedBy.getEmail());
            }

            // print other useful metadata
            System.out.println("  last updated: " + doc.getUpdated().toString());
            System.out.println("  viewed by user? " + doc.isViewed());
            System.out.println("  writersCanInvite? " + doc.isWritersCanInvite().toString());
            System.out.println("  hidden? " + doc.isHidden());
            System.out.println("  starrred? " + doc.isStarred());
            System.out.println();
        }
    }
}

please help , unable to find solution. thank you so much..looking for response

Original issue reported on code.google.com by somvit.b...@gmail.com on 9 May 2012 at 12:21

GoogleCodeExporter commented 9 years ago
I have the same problem when I tried to download text documents, I am not 
really sure if we have to move to the latest version of the API (known as 
Drive). the issue seems to be in 

MediaSource ms = docService.getMedia(mc);

I hope people from Google could provide some help please!!

Original comment by luisherd...@gmail.com on 20 May 2013 at 9:53

GoogleCodeExporter commented 9 years ago
I am also having this issue.  Has there been any solution?

Original comment by m...@trueaccord.com on 31 May 2014 at 7:05