A request can only have one entity body, that's why the restriction. The only option I can think of is to use multipart request, where you can have multiple body parts.
Example server side
@Path("multipart")
public class MultipartResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response doPost(@FormDataParam("emp") Emp emp,
@FormDataParam("student") Student student) {
StringBuilder builder = new StringBuilder();
builder.append("Emp:").append(emp.name).append("
");
builder.append("Student:").append(student.name).append("
");
return Response.ok(builder.toString()).build();
}
public static class Student {
public String name;
}
public static class Emp {
public String name;
}
}
Client side
public class Main {
public static void main(String[] args) throws Exception {
Client client = Client.create();
Emp emp = new Emp();
emp.name = "pee";
Student stu = new Student();
stu.name = "skillet";
FormDataMultiPart multipart = new FormDataMultiPart()
.field("emp", emp, MediaType.APPLICATION_JSON_TYPE)
.field("student", stu, MediaType.APPLICATION_JSON_TYPE);
final String url = "http://localhost:8080/api/multipart";
String response = client.resource(url).type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(String.class, multipart);
System.out.println(response);
}
}
Result:
Emp:pee
Student:skillet
Jersey dependency for multipart support.
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey1.version}</version>
</dependency>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…