我正在尝试创建一个实现所有四个 CRUD 操作的 RESTful Web 服务。我陷入了“创建”,因为不知何故我无法获得发布的数据。这是我写的方法。作为一个信息,我正在使用 JAX-RS + JAXB XML 的 Jersey RI 来序列化对象。
这里是:
@POST
@Consumes("application/xml")
public Response createStudent(InputStream is) {
Student st = this.readStudent(is);
st.setUserId(idCounter.incrementAndGet());
studentDB.put(st.getUserId(), st);
System.out.println("Created student " + st.getUserId());
return Response.created(URI.create("/student/"+ st.getUserId())).build();
}
readStudent 方法如下:
protected Student readStudent(InputStream is){
JAXBContext ctx;
Student st = null;
try {
String xml = is.toString();
System.out.println(xml);
ctx = JAXBContext.newInstance(Student.class);
st = (Student) ctx.createUnmarshaller().unmarshal(new StringReader(xml));
return st;
} catch (JAXBException e){
e.printStackTrace();
}
finally { return st; }
}
有人可以给我一些启发吗?我用尽了每一个想法来使它起作用,但没有任何效果!
提前致谢。
最佳答案
我认为您的问题是您使用 toString()
方法获取 InputStream
的字符串的行:
String xml = is.toString();
您应该读取输入流中的数据并将其附加到新字符串。 toString()
是流的字符串表示形式,但不是流的内容。您必须使用 InputStream
的 read
方法,并使用 StringBuilder
将字节附加到新的 String
或一个 StringWriter
。
关于java - RESTful Java Web 服务中的 POST 方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4101885/