Gmail REST API:400错误请求+失败的前提条件 [英] Gmail REST API : 400 Bad Request + Failed Precondition

查看:480
本文介绍了Gmail REST API:400错误请求+失败的前提条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用google java api服务发送基于Gmail REST API的邮件。我已经通过Google Develover Console配置了一个应用程序客户端并下载了p12和json文件。

I'm trying to send mails based on Gmail REST API using google java api services. I have configured through Google Develover Console an application client and downloaded p12 and json files.

我使用过这个示例程序, https://developers.google.com/gmail/api/guides/sending#sending_messages ...

I have used this sample programs, https://developers.google.com/gmail/api/guides/sending#sending_messages...

此示例有效,但这是基于GoogleAuthorizationCodeFlow。我只想从服务器到服务器工作,直接调用,而不是打开浏览器来获取访问令牌......我得到了它(访问令牌)但最后我收到了错误请求....为什么? ?我收到的信息不仅仅是 错误请求和先决条件失败

This sample works, but this is based on GoogleAuthorizationCodeFlow. I want just to work from server-to-server, invoking directly, not opening a browser to get an access token... and I got it (the access token) but finally i receive a Bad Request.... Why??? I don't receive more info just than "Bad Request" and "Precondition Failed"

基于此我按照以下步骤操作:

Based on this i follow the next steps:


  1. 第一步:根据我的客户帐户创建GoogleCredential对象mail和p12生成的文件:

  1. First Step: Create a GoogleCredential object based on my client account mail and p12 generated file:

GoogleCredential  credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
                                    .setJsonFactory(new JacksonFactory())
                                    .setServiceAccountId(serviceAccountUserEmail)
                                    .setServiceAccountScopes(scopes)
                                    .setServiceAccountPrivateKeyFromP12File(
                                                new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))                             
                                                        .build();


这里我必须指出我有很多使用ClientID而不是ClientMail的问题。它必须使用@ developer.gserviceaccount.com帐户而不是.apps.googleusercontent.com。如果你不发送这个参数确定,你会收到无效授予错误。这在此解释: https://developers.google.com/analytics/ devguides / config / mgmt / v3 / mgmtAuthorization

Here i have to point that i had many issues for ussing ClientID instead of ClientMail. It must use @developer.gserviceaccount.com account instead of .apps.googleusercontent.com . If u don't send this params ok , u get an "INVALID GRANT" error. This is explained here: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization


  1. 第二步:根据凭据创建Gmail服务:

  1. Second Step : Create the Gmail Service based on the credentials:

Gmail gmailService = new Gmail.Builder(httpTransport,
                                              jsonFactory,
                                              credential)
                                            .setApplicationName(APP_NAME)
                                                .build();


  • 第三步从MimmeMessage创建Google原始消息:

  • Third Step Create a Google raw message from a MimmeMessage:

    private static Message _createMessageWithEmail(final MimeMessage email) throws MessagingException, IOException {
    
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    email.writeTo(bytes);
    String encodedEmail =       Base64.encodeBase64URLSafeString(bytes.toByteArray());      
    Message message = new Message();    
    message.setRaw(encodedEmail);
    return message;
    

    }

    第四步调用服务:

        Message message = _createMessageWithEmail(email);
    message = service.users()
    .messages()
    .send(userId,message)
    .execute();
    


  • 第五步:执行后获取结果......我收到了例外:

  • Fifth Step : Get Result after execution...Here i receive the exception:
  • 线程main中的异常

    com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
    {
      "code" : 400,
      "errors" : [ {
        "domain" : "global",
        "message" : "Bad Request",
        "reason" : "failedPrecondition"
      } ],
      "message" : "Bad Request"
    }
        at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
    

    知道什么是错的或哪个是前提条件失败?

    推荐答案

    这就是我设法让它与Google Apps域协同工作的方式:

    This is how I managed to get it work with a Google Apps domain:

    1.-使用谷歌应用用户打开 开发者控制台

    1.- Using a google apps user open the developer console

    2.-创建一个新的项目(即 MyProject

    2.- Create a new project (ie MyProject)

    3。 - 转到[Apis& auth]> [凭据]并创建新的 [服务帐户] 客户ID

    3.- Go to [Apis & auth] > [Credentials] and create a new [Service Account] client ID

    4.-复制[服务帐户]的[客户ID](如xxx.apps.googleusercontent.com之类)供以后使用

    4.- Copy the [service account]'s [Client ID] (the one like xxx.apps.googleusercontent.com) for later use

    5.-现在您必须 删除域名范围内的服务帐户权限 ,以便授权您的appl代表Google Apps中的用户访问用户数据域名
    ...请转到 google apps域管理控制台

    5.- Now you have to Delegate domain-wide authority to the service account in order to authorize your appl to access user data on behalf of users in the Google Apps domain ... so go to your google apps domain admin console

    6.-转到[安全]部分找到[高级设置] (它可能是隐藏的,所以你必须点击[显示更多..])

    6.- Go to the [Security] section and find the [Advanced Settings] (it might be hidden so you'd have to click [Show more..])

    7.-点击con [管理API客户端访问]

    7.- Click con [Manage API Client Access]

    8.-粘贴[客户端]您之前在[4]中复制到[客户名称]文本框中的ID]。

    8.- Paste the [Client ID] you previously copied at [4] into the [Client Name] text box.

    9.-要将您的应用完全访问权限授予gmail,请在[API范围]文本框中输入: https://mail.google.com https:// www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/ gmail.modify https://www.googleapis.com/auth/gmail.readonly
    (输入所有范围非常重要)

    9.- To grant your app full access to gmail, at the [API Scopes] text box enter: https://mail.google.com, https://www.googleapis.com/auth/gmail.compose, https://www.googleapis.com/auth/gmail.modify, https://www.googleapis.com/auth/gmail.readonly (it's very important that you enter ALL the scopes)

    现在你'已完成所有设置...现在代码:

    Now you've done all the settings... now the code:

    1.-创建一个HttpTransport

    1.- Create an HttpTransport

    private static HttpTransport _createHttpTransport() throws GeneralSecurityException,
                                                               IOException { 
        HttpTransport httpTransport = new NetHttpTransport.Builder()                                                 
                                                          .trustCertificates(GoogleUtils.getCertificateTrustStore())
                              .build();
        return httpTransport;
    }
    

    2.-创建一个JSonFactory

    2.- Create a JSonFactory

    private static JsonFactory _createJsonFactory() {
        JsonFactory jsonFactory = new JacksonFactory();
        return jsonFactory;
    }
    

    3.-创建Google凭证

    3.- Create a google credential

    private static GoogleCredential _createCredentialUsingServerToken(final HttpTransport httpTransport,
                                                                      final JsonFactory jsonFactory) throws IOException,
                                                                                                            GeneralSecurityException {
        // Use the client ID when making the OAuth 2.0 access token request (see Google's OAuth 2.0 Service Account documentation).
        String serviceAccountClientID = "327116756300-thcjqf1mvrn0geefnu6ef3pe2sm61i2q.apps.googleusercontent.com"; 
    
        // Use the email address when granting the service account access to supported Google APIs 
        String serviceAccountUserEmail = "xxxx@developer.gserviceaccount.com";
    
        GoogleCredential credential = new GoogleCredential.Builder()
                                                    .setTransport(httpTransport)
                                                    .setJsonFactory(jsonFactory)
                                                    .setServiceAccountId(serviceAccountUserEmail)    // requesting the token
                                                    .setServiceAccountPrivateKeyFromP12File(new File(SERVER_P12_SECRET_PATH))
                                                    .setServiceAccountScopes(SCOPES)    // see https://developers.google.com/gmail/api/auth/scopes
                                                    .setServiceAccountUser("user@example.com")
                                                    .build();    
        credential.refreshToken();
        return credential;
    }
    

    注意:在setServiceAccountUser()方法中使用任何来自您的Google应用领域的用户

    NOTE: At setServiceAccountUser() method use any user from your google apps domain

    4.-创建Gmail服务

    4.- Create a Gmail Service

    private static Gmail _createGmailService(final HttpTransport httpTransport,
                                             final JsonFactory jsonFactory,
                                             final GoogleCredential credential) {
        Gmail gmailService = new Gmail.Builder(httpTransport,
                                                jsonFactory,
                                                credential)
                                       .setApplicationName(APP_NAME)
                                       .build();
        return gmailService;
    }
    

    现在,您可以使用GmailService执行任何操作,例如发送电子邮件; - )如 https://developers.google.com/gmail/api/guides/sending 所述

    Now you can do whatever you want with the GmailService like send an email ;-) as described at https://developers.google.com/gmail/api/guides/sending

    这篇关于Gmail REST API:400错误请求+失败的前提条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆