我正在尝试使用 @Produces
、@Consumes
注释和 JAXB 创建并运行 JAX-RS 的简单示例。
@Stateless
@LocalBean
@Path("/hotel")
public class RestMain {
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{hotelId}")
public HotelRESTInfo read(@PathParam("hotelId") long hotelId) {
HotelDataSourceFake hotelDataSourceFake = new HotelDataSourceFake();
HotelRESTInfo hotelInfo = hotelDataSourceFake.getFakePlaceById(hotelId);
return hotelInfo;
}
}
web.xml:
<servlet>
<servlet-name>REST App</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
第二个应用程序是客户端。 现在我有以下客户端代码:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
...
Client client = Client.create();
String uri ="http://localhost:8080/RESTJEE/rest/hotel/" + hotelId;
WebResource resource = client.resource(uri);
ClientResponse response = resource.accept("application/xml").get(ClientResponse.class);
HotelRESTInfo hotelRestInfo = response.getEntity(HotelRESTInfo.class);
但是我不想用jersey的Client,ClientResponse和WebResource。
我想用 @Consumes
来做到这一点。
客户端应用程序 web.xml
是否应该包含一些额外的参数?
双方(客户端和服务器)都包含 HotelRESTInfo
类:
@XmlRootElement
public class HotelRESTInfo {
...
}
最佳答案
我认为你不匹配某些东西。
您在一侧有发出请求的 HttpClient,在另一台计算机上有构建响应的 HttpServer。这是基本的,我想你明白了。
事情是@GET read ()method
消费请求主体,并产生响应主体。
所以你可以:
@GET
@Consumes(MediaType.APPLICATION_XML) //client sends also xml
@Produces(MediaType.APPLICATION_XML)
@Path("{hotelId}")
public HotelRESTInfo read(@PathParam("hotelId") long hotelId) {
(...)
}
显然,您希望您的客户端使用网络服务,因此@Consume
在客户端绝对有意义。
不幸的是,JaxRS 是在 2008 年左右在服务器端构建的,没有考虑与 Java 客户端的协同作用。而@Consumes 绝对是一个服务器注解,我在documentation anything about reusing 中没有看到客户端上的注释。
Jersey 客户端是最新的,符合 JaxRS 2 规范。你的问题表明这些规范可能很难写!
关于java - 使用@Consumes、@Produces 和 JAXB 的简单 JAX-RS 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987912/