HTTP 400 error in REST web service during POST with FormParam containing own objects (e.g. enities)

徘徊边缘 提交于 2019-12-01 06:48:24

Due to the new information that the entity "Kunde" isn't trasmitted correctly I found a
SOLUTION:

I explicitely transformed the entity class into XML/JSON (either way is working) and put that XML/JSON as a String in the form. On the server's side I transformed the XML/JSON String back into the Entity, this worked.
(Seems like it is NOT possible to transmit an object not beeing String or Integer as it is.)

Hope this will help everyone who faces the same problem transmitting objects from client to server via REST.
(Sending a List of XML/JSON-converted objects is still to test. I'll add the result here soon.)

Greetings and thanks to chrylis for his/her comments and hints.
Jana


Here's the code for the solution, but for shortness it's only the new parts.

1) The XML solution:

For changing Entity into XML String on Client's side:

...
OutputStream out = new ByteArrayOutputStream();

JAXBContext context = JAXBContext.newInstance(Kunde.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(kunde, out);
out.close();

Form form = new Form();
form.add("entity", out.toString());
...

For transforming the XML back to an Object on the Server's side:

...
public String test(
    @FormParam("entity") String entityString) {      

    InputStream inputStream = new ByteArrayInputStream(entityString.getBytes());        
    Kunde kunde = JAXB.unmarshal(inputStream, Kunde.class);       

    return "Der Name des Kunden ist: "+kunde.getVorname()+" "+kunde.getNachname();
}


2) The JSON solution:

For changing Entity into JSON String on Client's side:

...
OutputStream out = new ByteArrayOutputStream();

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(out, kunde);
out.close();

Form form = new Form();
form.add("entity", out.toString());
...

For transforming the JSON String back to an Object on the Server's side:

...
public String test(
    @FormParam("entity") String entityString) {      

    InputStream inputStream = new ByteArrayInputStream(entityString.getBytes());        
    Kunde kunde = new ObjectMapper().read((inputStream, Kunde.class));       

    return "Der Name des Kunden ist: "+kunde.getVorname()+" "+kunde.getNachname();
}

The classes JAXB, JAXBContext, Marshaller etc. are from package javax.xml.bind.*. The class ObjectMapper is from package org.codehaus.jackson.map.*.

PS: Because transmitting plain String now, you also could use @QueryParam. But I wouldn't recomment that, because you'd be transmitting the whole XML as a text String in the URL. Same goes for @PathParam.

I'd recommend JSON, because the format is more slender than the XML format, and being slender is the aim of REST.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!