本文介绍了REST Web服务(Jersey)中的HTTP 204错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey/Java开发我的REST服务.我需要为CarStore返回XML表示形式:

I am using Jersey/Java to develop my REST services. I need to return an XML representation for my CarStore :

 @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;
 }

}

规格和类别是这样的枚举:

Specs and Category are enums like this :

    @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错误以及客户端异常:

I am getting Http 204 error on access alongwith client exception :

有什么想法吗?谢谢 !

Any ideas ? Thanks !

我还没有开发模型类...我只是将一些汽车对象初始化为虚拟数据并将其放入汽车商店.在这里显示所有课程将非常笨拙.顺便说一句,很抱歉写了204 Error ..仅仅是因为我遇到了一个异常,所以我才这么认为.

EDIT : I have yet not developed the model class...I just initialized some car objects as dummy data and put them in carstore. Showing all the classes here would be very clumsy.BTW, sorry for writing 204 Error..it is just that I am getting an Exception that led me think so.

推荐答案

我相信您会得到一个UniformInterfaceException,因为您的getCars()函数未返回HTTP响应主体.根本问题是JAXB不会将您的汽车清单转换为XML,因为它缺少@XmlElement批注.

I believe you are getting a UniformInterfaceException because your getCars() function is not returning an HTTP response body. The root problem is that your Car List isn't being converted into XML by JAXB because it is missing the @XmlElement annotation.

您的getCars()函数应为:

Your getCars() function should be:

@GET
@Produces(MediaType.APPLICATION_XML)
public CarStore getCars() {
    // myCarStore is an instance of CarStore
    return myCarStore.getCars();
}

,并且应该定义您在CarStore中的汽车清单:

and your Car List in CarStore should be defined:

@XmlElement(name="car")
private List<Car> cars;

这篇关于REST Web服务(Jersey)中的HTTP 204错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 21:28