如何将HTTPBasicAuthFilter指定为Play的WS调用?

时间:2014-03-23 03:21:54

标签: java email playframework playframework-2.0 mailgun

我想用Play的WS api打电话给Mailgun服务。 Mailgun要求发送用于身份验证的API密钥,并根据他们的' jersey'客户端示例,他们将此API密钥指定为' HTTPBasicAuthFilter'与客户,如下:

public static ClientResponse SendSimpleMessage() {
       Client client = Client.create();
       client.addFilter(new HTTPBasicAuthFilter("api",
                       "key-3ax6xnjp29jd6fds4gc373sgvjxteol0"));
       WebResource webResource =
               client.resource("https://api.mailgun.net/v2/samples.mailgun.org" +
                               "/messages");
       MultivaluedMapImpl formData = new MultivaluedMapImpl();
       formData.add("from", "Excited User <me@samples.mailgun.org>");
       formData.add("to", "bar@example.com");
       formData.add("to", "baz@example.com");
       formData.add("subject", "Hello");
       formData.add("text", "Testing some Mailgun awesomness!");
       return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).
               post(ClientResponse.class, formData);
}

如何使用Play的WS api做同样的事情?

2 个答案:

答案 0 :(得分:0)

我在WS课程中徘徊了一段时间后想通了。这就是我的所作所为。

    public class MailHelper {

    public static Promise<WS.Response> send(EmailData emailData) {
        WSRequestHolder mailGun = WS.url("https://api.mailgun.net/v2/feedmerang.com/messages");
        mailGun.setAuth("api", "MAILGUN_API_KEY");
        mailGun.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        mailGun.setQueryParameter("from", emailData.from);
        mailGun.setQueryParameter("to", emailData.to);
        mailGun.setQueryParameter("subject", emailData.subject);
        mailGun.setQueryParameter("html", emailData.body);
        return mailGun.post("Sending Email");
    }
}

答案 1 :(得分:0)

使用WS withAuth:

WS.url(apiUrl).withAuth("api", apiKey, WSAuthScheme.BASIC).post(postMessage)
  • apiUrl是您要发布到

  • 的网址
  • apiKey是来自mailgun的密钥

  • postMessage是String到Seq of String的Map。在Scala中Map[String, Seq[String]],如下所示:

    val postMessage = Map("from" -> Seq(message.from), "to" -> Seq(message.to), "subject" -> Seq(message.subject), "text" -> Seq(message.text), "html" -> Seq(message.html.toString()))