【问题标题】:Google Api spreadsheets with java- Error -com.google.gdata.util.ServiceException: Method Not Allowed带有 java-Error -com.google.gdata.util.ServiceException: Method Not Allowed 的 Google Api 电子表格
【发布时间】:2016-05-17 19:21:24
【问题描述】:

我已经完成了 oauth 2.0 身份验证并获得了令牌。现在,当我尝试添加工作表时,我在 service.insert 上遇到错误。

有 2 个类,一个是我获取令牌的地方,另一个是我传递凭据然后添加工作表的地方 -:

请看以下代码-:

第一类

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.gdata.util.ServiceException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class OAuth2Sample{

  // Retrieve the CLIENT_ID and CLIENT_SECRET from an APIs Console project:
  //     https://code.google.com/apis/console
  static String CLIENT_ID = "cilent id";
  static String CLIENT_SECRET = "client secret
";
  // Change the REDIRECT_URI value to your registered redirect URI for web
  // applications.
  static String REDIRECT_URI = "http://www.google.com";
  // Add other requested scopes.
  static List<String> SCOPES = Arrays.asList("https://spreadsheets.google.com/feeds");


public static void main (String args[]) throws IOException, ServiceException {
    Credential credencial = getCredentials();
    Abc.printDocuments(credencial);
}


  /**
   * Retrieve OAuth 2.0 credentials.
   * 
   * @return OAuth 2.0 Credential instance.
   */
  static Credential getCredentials() throws IOException {
    HttpTransport transport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    // Step 1: Authorize -->
    String authorizationUrl =
        new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).build();

    // Point or redirect your user to the authorizationUrl.
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Read the authorization code from the standard input stream.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String code = in.readLine();
    // End of Step 1 <--

    // Step 2: Exchange -->
    GoogleTokenResponse response =
        new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
            code, REDIRECT_URI).execute();
    // End of Step 2 <--
       System.out.println(response);
    // Build a new GoogleCredential instance and return it.
    return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET)
        .setJsonFactory(jsonFactory).setTransport(transport).build()
     .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
  }

  // …
}

2 级

    import com.google.api.client.auth.oauth2.Credential;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.PlainTextConstruct;

import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;

import java.io.IOException;
import java.net.*;
import java.util.*;
import com.google.gdata.util.ServiceException;

// ...



    // ...

    public class Abc {
      // …

      static void printDocuments(Credential credential) throws IOException, ServiceException {
        // Instantiate and authorize a new SpreadsheetService object.

          SpreadsheetService service = new SpreadsheetService("Application-Name"); // Dont know exactly what comes here
          service.setProtocolVersion(SpreadsheetService.Versions.V3); // It's important to specify the version


          System.out.println(credential);
          service.setOAuth2Credentials(credential);
                // TODO: Authorize the service object for a specific user (see other sections)

                // Define the URL to request.  This should never change.
                System.out.println("hello");
                URL SPREADSHEET_FEED_URL = new URL(
                    "https://spreadsheets.google.com/feeds/worksheets/1svU1AqLz0wPpUeYTrTx4QALbV3Mb4GM3YJklrl_BAfQ/public/full");
                System.out.println("hello1");
                // Make a request to the API and get all spreadsheets.
                SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
                    SpreadsheetFeed.class);
                System.out.println(feed);
                List<SpreadsheetEntry> spreadsheets = feed.getEntries();
                System.out.println(spreadsheets);
                if (spreadsheets.size() == 0) {
                  // TODO: There were no spreadsheets, act accordingly.
                }

                // TODO: Choose a spreadsheet more intelligently based on your
                // app's needs.
                SpreadsheetEntry spreadsheet = spreadsheets.get(0);
                System.out.println(spreadsheet.getTitle().getPlainText());

                // Create a local representation of the new worksheet.
                WorksheetEntry worksheet = new WorksheetEntry();
                worksheet.setTitle(new PlainTextConstruct("New Worksheet"));
                worksheet.setColCount(10);
                worksheet.setRowCount(20);

                // Send the local representation of the worksheet to the API for
                // creation.  The URL to use here is the worksheet feed URL of our
                // spreadsheet.
                URL worksheetFeedUrl = spreadsheet.getWorksheetFeedUrl();
                System.out.println(worksheetFeedUrl);
                service.insert(worksheetFeedUrl, worksheet);

      }  // ...
    }

【问题讨论】:

    标签: java oauth google-spreadsheet-api


    【解决方案1】:

    HTTP 405 表示您正在尝试使用资源不允许的动词。例如,在仅就绪的GET 资源上使用POST 或在仅接受POST 的写入资源上使用PUT

    https://accounts.google.com/o/oauth2/token
    

    如果请求被发送到http://,它会被重定向到https,在这个过程中,POST 变成了GET,因此会出现错误消息。

    AccessToken 和 RefreshToken 的交换验证码。请注意,这需要作为 HTTP POST 而不是 HTTP Get 发送。

    https://accounts.google.com/o/oauth2/token
    code={Authentication Code from step 1}&client_id={ClientId}.apps.googleusercontent.com&client_secret= {ClientSecret}&redirect_uri=={From console}&grant_type=authorization_code
    

    你应该得到一个类似这样的 JSON 字符串。

    {
    "access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
    "token_type" : "Bearer",
    "expires_in" : 3600,
    "refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
    }
    

    现在您可以获取该 Access_token 并使用它来提出您的请求。但是访问令牌只能使用 1 小时,然后它们会在此之前过期,您需要使用 Refresh_token 来获取新的访问令牌。此外,如果您想再次访问您的用户数据,您应该将 refresh_token 保存在某个位置,这样您就可以始终访问那里的数据。

    有关更多信息,请查看 Google 3 Legged OAuth2 流程:http://www.daimto.com/google-3-legged-oauth2-flow/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2011-11-17
      • 2018-06-28
      • 1970-01-01
      相关资源
      最近更新 更多