繁体   English   中英

Java客户端使用API

[英]java client consuming API

我正在尝试使用Mail Gun API来获取退回邮件数据。

public static ClientResponse GetBounce() {

     Client client = new Client();
           client.addFilter(new HTTPBasicAuthFilter("api",
                           "key-XXXXXXXXXXXXXXXXXXXXX"));
           WebResource webResource =
                   client.resource("https://api.mailgun.net/v3/XXXXXXXXXXXX.mailgun.org/" +
                                   "bounces/foo@bar.com");
    return webResource.get(ClientResponse.class);}

它可以正常工作,可以进行API调用,但是我无法在cae EmailError中将ClientResponse转换为适当的类型。 来自服务器的实际响应为{"address":"a@gmail.com","code":"550","error":"550 5.2.1 The email account that you tried to reach is disabled. lq5si9613879igb.63 - gsmtp","created_at":"Tue, 18 Aug 2015 12:23:35 UTC"}

我创建了POJO来映射响应

@JsonAutoDetect(getterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
@JsonSerialize(include = Inclusion.NON_NULL)
public class EmailError {
    private String address;
    private String error;
    private String created_at;
//geters...
//setters..
}

并尝试将ClientResponse映射到EmailError类型。

ClientResponse clientResponse = getBounce(email);
         EmailError error = response.getEntity(new GenericType<EmailError>() {
         });

其中clientResponse是通过方法GetBounce()返回的对象

It throws an Exception com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class com.che.rt.businessservices.EmailError, and Java type class com.che.rt.businessservices.EmailError, and MIME media type application/json;charset=utf-8 was not found

任何我想念的地方。

您似乎具有Jackson依赖关系(因为您正在使用其批注),但这对Jersey而言还不够。 Jersey使用MessageBodyReader来反序列化请求/响应正文。 因此,您需要一个可以处理JSON的应用程序。 Jackson确实实现了JAX-RS读取器和写入器。 因此,您需要的依赖项是Jackson提供程序,而不仅仅是主要的Jackson库。

对于Jersey,您可以添加此依赖项

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19</version>
</dependency>

这将引入Jackson 1.9.2,因此您可以摆脱拥有的其他Jackson依赖项,以免版本冲突。 然后,您需要向Jersey客户端注册Jackson提供商。 为此,你可以做

ClientConfig config = new DefaultClientConfig();
config.getProperties().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
config.getSingletons().add(new JacksonJsonProvider());
Client client = Client.create(config);

注意上面使用杰克逊1.9.2。 如果要使用较新的2.x Jackson,请使用上面的依赖项,而不是上面的依赖项

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <!-- or whatever [2.2,) version you want to use -->
    <version>2.5.0</version>
</dependency>

然后配置也应该不同

ClientConfig config = new DefaultClientConfig();
config.getSingletons().add(new JacksonJsonProvider());
Client client = Client.create(config);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM