How to submit multiple entities to the post method from jersey client program?(如何从泽西客户端程序向 post 方法提交多个实体?)
问题描述
我正在尝试将多个实体传递给 Web 服务方法.web服务方法有两个pojo实体类型参数.我只能将一个实体发布到 Web 服务方法.我无法将多个实体发布到 Web 服务方法.
I am trying to pass multiple entities to the web service method. The web service method has two parameters of pojo entity type. I am able to post only one entity to the web service method. I am unable to post multiple entities to the web service method.
Server side code:
@POST
@Path("/test")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public void testMethod(Emp emp, Student stud){
...
}
Client side code:
...
...
Emp emp = new Emp;
Student stud = new Student();
ClientResponse response = resource.type(MediaType.APPLICATION_XML).entity(emp).entity(stud).post(ClientResponse.class);
推荐答案
一个请求只能有一个实体主体,这就是限制的原因.我能想到的唯一选择是使用 multipart request,你可以有多个身体部位.
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.
示例服务器端
@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;
}
}
客户端
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);
}
}
结果:
Emp:小便
学生:煎锅
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>
这篇关于如何从泽西客户端程序向 post 方法提交多个实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从泽西客户端程序向 post 方法提交多个实体?


- 如何使用WebFilter实现授权头检查 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01