【问题标题】:SendGrid: "The provided authorization grant is invalid, expired, or revoked"SendGrid:“提供的授权授权无效、过期或撤销”
【发布时间】:2019-11-08 20:31:30
【问题描述】:

我正在设置一个应用程序来向客户发送电子邮件。我正在使用 Java 和 SendGrid 创建这个应用程序,但我遇到了 SendGrid 授权问题

我收到错误:

java.io.IOException: 请求返回状态码 401Body:{"errors":[{"message":"提供的授权授权无效、过期或撤销","field":null,"help":空}]}

阅读其他一些类似问题的帖子,似乎大多数都得到了解决,因为人们使用的是 API Key ID 而不是 API Key。我已经检查过以确保我使用的是完整密钥,所以我认为这不是问题。

我也尝试创建一个新的 API 密钥,但这只是给出了同样的问题。最后,我尝试使用 Postman 进行类似的调用,并且使用相同的 API 密钥效果很好。

这是我用来发送电子邮件的主要类。


import com.sendgrid.*;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;

import java.io.IOException;

public class SendEmail {

    public static void main(String[] args) throws IOException{
        Email from = new Email("FROM_EMAIL");
        String subject = "Sending with Twilio(?) is fun";
        Email to = new Email("TO_EMAIL");
        Content content = new Content("text/plain", "and easy to to anywhere, even with Java");
        Mail mail = new Mail(from, subject, to, content);

        SendGrid sg = new SendGrid(System.getenv("API_KEY"));
        Request request = new Request();

        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw(ex);
        }

    }

然后我通过这个 sn-p 在我的主类中调用这个类:


    try{
            SendEmail.main(email);
    } catch(IOException ex){
            System.out.println(ex);
    }

“email”字符串只是一个占位符,否则我会收到一条错误消息,提示我在调用类时需要一个数组。 (不知道为什么会这样,这可能是问题的根源吗?)

显然敏感信息已被删除,这就是为什么某些字段看起来不正常的原因。

顺便说一下,我是按照这个github上的教程做的:

https://github.com/sendgrid/sendgrid-java

让我知道你的想法。 提前致谢!

【问题讨论】:

    标签: java authorization sendgrid sendgrid-api-v3


    【解决方案1】:

    我认为您的环境变量设置不正确。尝试执行没有“System.getenv”的程序,如下所示。

    SendGrid sg = new SendGrid("YOUR_API_KEY");
    

    【讨论】:

      【解决方案2】:

      我很抱歉。我不知道“System.getenv”会得到环境变量。我设置了环境变量,问题就解决了。

      【讨论】:

        猜你喜欢
        • 2019-03-29
        • 2017-03-20
        • 2016-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多