Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CXF JAXRS - How to POST more than one parameter

How do I send more than one parameter in request body in a POST request?

@POST
@Consumes("multipart/form-data")
@Produces("application/json")
public String addForm1(@FormParam("i1") Integer i1, @FormParam("i2") Integer i2);

Above code returns HTTP 415.

Replacing @FormParam with @Multipart results in Resource method has more than one parameter representing a request body error, as shown below.

SEVERE: Resource method service.rs.TestService.postData2 has more than one parameter representing a request body
Exception in thread "main" org.apache.cxf.jaxrs.client.ClientWebApplicationException: Resource method service.rs.TestService.postData2 has more than one parameter representing a request body
at org.apache.cxf.jaxrs.client.ClientProxyImpl.reportInvalidResourceMethod(ClientProxyImpl.java:546)
at org.apache.cxf.jaxrs.client.ClientProxyImpl.getParametersInfo(ClientProxyImpl.java:214)
at org.apache.cxf.jaxrs.client.ClientProxyImpl.invoke(ClientProxyImpl.java:138)
at $Proxy20.postData2(Unknown Source)
at service.TestServiceClient.main(TestServiceClient.java:82)

Also, what do I need to do in order to pass multiple complex types such as List<Map<String, String>>' or 'List<MyNestedCustomObject> in a POST method? I'm able to pass such parameter by using JAXB and annotating it with @XmlJavaTypeAdapter, but I guess that doesn't work in case of passing multiple parameters? Would I be required to define my own message body readers & writers? Any sample code would be useful.

Thanks

like image 710
domino Avatar asked Oct 08 '22 11:10

domino


1 Answers

I figured a way to do this (see code below). But if you know a better way, which preferably does not use the concept of "attachments" and uses jaxrs:client directly instead of WebClient, please let me know.

Service:

@POST 
@Path("/postdata3") 
@Consumes("multipart/mixed") 
@Produces("application/json") 
public String postData3(@Multipart(value = "testItem1", type = "application/json") TestItem t1, 
    @Multipart(value = "testItem2", type = "application/json") TestItem t2 
    ); 

Client:

    WebClient client = WebClient.create("http://myserver/services/test/postdata3"); 
    client.type("multipart/mixed").accept("application/json"); 
    List<Attachment> atts = new LinkedList<Attachment>(); 
    atts.add(new Attachment("testItem1", "application/json", t1)); 
    atts.add(new Attachment("testItem2", "application/json", t2)); 
    javax.ws.rs.core.Response s = client.postCollection(atts, Attachment.class); 
    System.out.println(s.getStatus());
like image 81
domino Avatar answered Oct 12 '22 12:10

domino