0

我正在尝试通过网络服务发送电子邮件。AhcCurlRequestLogger当我将其粘贴到终端时,记录的 curl 脚本工作正常。但服务方法不起作用。代码不输入wsResponse部分。

java函数:

public CompletionStage<String> sendEmail(String to, String subject, String content) {

    JsonNode requestBody = new ObjectMapper().createObjectNode()
            .put("username", this.apiUsername)
            .put("api_key", this.apiKey)
            .put("from", this.mailFrom)
            .put("bcc", this.mailBcc)
            .put("reply_to", this.mailFrom)
            .put("recipient", to)
            .put("subject", subject)
            .put("campaign_name", subject)
            .put("raw_html", content);

    return ws.url(this.apiUrl)
            .setRequestFilter(new AhcCurlRequestLogger())
            .post(requestBody)
            .thenApply((WSResponse wsResponse) -> {
                int responseStatus = wsResponse.getStatus();
                if (responseStatus >= 200 && responseStatus < 300) {
                    log.info("An email with subject " + subject + " was sent successfully to: " + to);
                    return "Mail was sent successfully.";
                } else {
                    log.error("An email with subject " + subject + " could not send successfully to: " + to);
                    return "Mail could not sent successfully.";
                }
            });
} 

卷曲脚本:

  [info] p.l.w.a.AhcCurlRequestLogger - curl \
    --verbose \
    --request POST \
    --header 'Content-Type: application/json' \
    --data '{
    "username" : "secret_username",
    "api_key" : "secret_key",
    "from" : "some@mail.com",
    "bcc" : "some@mail.com",
    "reply_to" : "some@mail.com",
    "recipient" : "some@mail.com",
    "subject" : "top_secret",
    "campaign_name" : "top_secret",
    "raw_html" : "<h3>super mail</h3>"
  }' \
    'https://madmimi.com/api/v3/transactionalEmails'

我没有任何错误日志。我正在使用 playframework 2.7.3 版本。我虽然那个ssl验证可能会导致这个。所以我将 ssl 证书链添加到 trustStore。这没用。然后我删除它并添加

play.ws.ssl.loose.acceptAnyCertificate = true

application.conf. 它也不起作用。

4

1 回答 1

0

仅当返回的承诺成功完成时,您的代码片段中的日志才会运行.post(requestBody)。因此,似乎有一个异常阻止了承诺的完成。

要处理这种情况,您可以添加exceptionally- 方法:

    return ws.url(this.apiUrl)
        .setRequestFilter(new AhcCurlRequestLogger())
        .post(requestBody)
        .thenApply((WSResponse wsResponse) -> {
            ...
        })
        .exceptionally(throwable -> {
            log.error("The request failed", throwable);
            return "Mail could not be sent successfully.";
        });

当您记录错误时,如何修复它可能很明显。如果不是,请将错误添加到问题中。

于 2019-09-02T13:09:22.827 回答