作者:风一样的梦 | 来源:互联网 | 2023-05-19 06:30
我正在尝试使用@Produces,@Consumes注释和JAXB创建和运行JAX-RS的简单示例.@Stateless@LocalBean@Path(hotel)public
我正在尝试使用@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中:
REST App
com.sun.jersey.spi.container.servlet.ServletContainer
1
Jersey Web Application
/rest/*
第二个应用程序是客户端.
现在我有以下客户端代码:
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做这个.
客户端appliaction web.xml是否应包含一些其他参数?
双方(客户端和服务器)包含HotelRESTInfo类:
@XmlRootElement
public class HotelRESTInfo {
...
}
解决方法:
我认为你是不匹配的东西.
一方面有HttpClient发出请求,另一方面有HttpServer构建响应.这是基本的,我想你得到它.
问题是@GET read()方法使用请求体,并生成响应体.
所以你可以:
@GET
@Consumes(MediaType.APPLICATION_XML) //client sends also xml
@Produces(MediaType.APPLICATION_XML)
@Path("{hotelId}")
public HotelRESTInfo read(@PathParam("hotelId") long hotelId) {
(...)
}
显然,您希望您的客户端使用Web服务,因此@Consume在客户端明确有意义.
不幸的是,JaxRS是在2008年左右在服务器端构建的,没有考虑与Java客户端的协同作用. @Consumes绝对是一个服务器注释,我没有在客户端的documentation anything about reusing注释中看到过.
在JaxRS 2规范的努力下,Jersey客户端是最新的.您的问题表明这些规格可能很难写!