Dou*_*ter 14
3.0测试文档这里介绍,像这样这些弃用:
Resteasy手动客户端API,拦截器,StringConverters,StringParamterConverters和Async HTTP API都已被弃用,可能会在以后的版本中删除.现在有一个JAX-RS 2.0等同于这些东西.
这将意味着,优选的方法将是使用在所描述的JAX-RS客户端API 此篇
如果我们假设有一个JSON API http://example.org/pizza/{id}.json,(其中'id'是比萨饼ID)返回结果,例如
{
"name": "Hawaiian",
"toppings": ["tomato", "ham", "cheese", "pineapple"]
}
Run Code Online (Sandbox Code Playgroud)
在Invocation.BuilderJavadocs的基础上,我们可以做这样的事情,
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import org.glassfish.jersey.jackson.JacksonFeature;
public class PizzaClient {
private Client client;
public PizzaClient() {
client = ClientBuilder.newClient();
// enable POJO mapping using Jackson - see
// https://jersey.java.net/documentation/latest/user-guide.html#json.jackson
client.register(JacksonFeature.class);
}
/** POJO which maps to JSON results using Jackson */
public static class Pizza {
private String name;
private String[] toppings;
public String getName() { return name; }
public String[] getToppings() { return toppings ; }
}
public Pizza getPizzaById(String id) {
String uri = String.format("http://example.org/pizza/%s.json", id)
Invocation.Builder bldr = client.target(uri).request("application/json");
return bldr.get(Pizza.class);
}
public static void main(String[] args) {
PizzaClient pc = new PizzaClient();
Pizza pizza = pc.getPizzaById("1");
System.out.println(pizza.getName() + ":");
for (String topping : pizza.getToppings()) {
System.out.println("\t" + topping);
}
}
}
Run Code Online (Sandbox Code Playgroud)
(这也是辅助这个帖子虽然说使用的是弃用API).
另请注意,如果您想使用Jackson读取POJO(或者,我认为,使用JAXB),您可能需要注册一个特殊的处理程序,如此处所述
更新 您实际上只需要以下Maven依赖项:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.3.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
(在这种情况下,您根本不使用RestEasy - javax.ws.rsJAXRS实现来自Jersey)
或者你可以坚持使用JBoss:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.4.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以在上面的代码中删除JacksonFeature行,代码使用更自由的Apache许可证.