Lan*_*erX 4 java rest web-services jax-rs java-ee
我正在尝试使用@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;
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
第二个应用程序是客户端.现在我有以下客户端代码:
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);
Run Code Online (Sandbox Code Playgroud)
但我不想使用jersey的Client,ClientResponse和WebResource.我想这样做@Consumes
.客户端应用程序是否应web.xml
包含一些其他参数?
双方(客户端和服务器)包含HotelRESTInfo
类:
@XmlRootElement
public class HotelRESTInfo {
...
}
Run Code Online (Sandbox Code Playgroud)
我认为你是不匹配的东西.
一方面有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) {
(...)
}
Run Code Online (Sandbox Code Playgroud)
显然,您希望您的客户端使用Web服务,因此@Consume
在客户端确实有意义.
不幸的是,JaxRS是在2008年左右在服务器端构建的,没有考虑与Java客户端的协同作用.@Consumes绝对是一个服务器注释,我没有在文档中看到有关在客户端重用注释的任何信息.
在JaxRS 2规范的努力下,Jersey客户端是最新的.您的问题表明这些规格可能很难写!
归档时间: |
|
查看次数: |
15421 次 |
最近记录: |