我正在使用Jersey / Java来开发我的REST服务。我需要为CarStore返回XML表示:
@XmlRootElement
public class CarStore {
private List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
这是我的Car对象:
@XmlRootElement
> public class Car {
private String carName;
private Specs carSpecs;
private Category carCategory;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public Specs getCarSpecs() {
return carSpecs;
}
public void setCarSpecs(Specs carSpecs) {
this.carSpecs = carSpecs;
}
public Category getCarCategory() {
return carCategory;
}
public void setCarCategory(Category carCategory) {
this.carCategory = carCategory;
}
}
规格和类别是这样的枚举:
@XmlRootElement
> public enum Category {
SEDANS, COMPACTS, WAGONS, HATCH_HYBRIDS, SUVS, CONVERTIBLES, COMPARABLE;
}
我的资源类是:
@GET
@Produces({MediaType.APPLICATION_XML})
public CarStore getCars()
{
return CarStoreModel.instance.getAllCars();
}
我的球衣客户是:
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("rest").path("cars").accept(
MediaType.APPLICATION_XML).get(String.class));
我在访问时遇到Http 204错误以及客户端异常:
com.sun.jersey.api.client.UniformInterfaceException
有什么想法吗?谢谢 !
编辑:我还没有开发模型类...我只是将一些汽车对象初始化为虚拟数据并将它们放入汽车库中。在这里展示所有课程将非常笨拙。 顺便说一句,抱歉写了204错误..这只是因为我得到了一个例外,导致我这么认为。答案 0 :(得分:3)
我猜测异常与响应代码(204)无关,因为204是表示“无内容”的成功条件。
答案 1 :(得分:0)
您是以xml格式返回的吗?我不确定getAllCars是做什么的,但是你可以使用类似Fiddler的东西来帮助你查看流量,看看返回给客户端的内容以及它的格式是否正确等等
答案 2 :(得分:0)
在您的客户端代码中,资源路径是否正确?确保getBaseURI
返回一个值。
也许试试:
Client client = new Client();
WebResource resource = client.resource(getBaseURI());
CarStore carStore = resource.path("/rest/cars").accept(MediaType.APPLICATION_XML).get(CarStore.class);
答案 3 :(得分:0)
我相信你得到UniformInterfaceException
,因为你的getCars()
函数没有返回HTTP响应正文。根本问题是JAXB没有将您的Car List转换为XML,因为它缺少@XmlElement
注释。
你的getCars()函数应该是:
@GET
@Produces(MediaType.APPLICATION_XML)
public CarStore getCars() {
// myCarStore is an instance of CarStore
return myCarStore.getCars();
}
并且应该定义CarStore中的车辆清单:
@XmlElement(name="car")
private List<Car> cars;
答案 4 :(得分:0)
您是否错过了资源类的@Path注释?
@GET
@Path("cars")
@Produces({ MediaType.APPLICATION_XML })
public CarStore getCars() {
return CarStoreModel.instance.getAllCars();
}
通过在getCars()方法中放置断点(或放置System.out.println)以确保实际调用它,检查REST WS挂载的URL是否是您期望的URL。
答案 5 :(得分:0)
似乎在Jersey中有一个硬编码检查,在返回HTTP 204时抛出UniformInterfaceException。
最好的解决方案是“修复”其余服务器,以便它永远不会返回null。例如返回空列表或未设置值的类。
否则你需要捕获非常丑陋的UniformInterfaceException
if (getStatus() == 204) {
throw new UniformInterfaceException(this);
}