REST - 带有JSON的HTTP Post Multipart

the*_*rmz 86 java rest json http resteasy

我需要收到一个HTTP Post Multipart,它只包含2个参数:

  • 一个JSON字符串
  • 二进制文件

设置身体的正确方法是什么?我将使用Chrome REST控制台测试HTTP调用,所以我想知道正确的解决方案是为JSON参数和二进制文件设置"标签"键.

在服务器端我正在使用Resteasy 2.x,我将阅读这样的Multipart主体:

@POST
@Consumes("multipart/form-data")
public String postWithPhoto(MultipartFormDataInput  multiPart) {
  Map <String, List<InputPart>> params = multiPart.getFormDataMap();
  String myJson = params.get("myJsonName").get(0).getBodyAsString();
  InputPart imagePart = params.get("photo").get(0);
  //do whatever I need to do with my json and my photo
}
Run Code Online (Sandbox Code Playgroud)

这是要走的路吗?使用标识特定内容处置的键"myJsonName"检索我的JSON字符串是否正确?有没有其他方法可以在一个HTTP多部分请求中接收这两个内容?

提前致谢

Vas*_*nov 142

如果我理解正确,您希望从HTTP/REST控制台手动编写多部分请求.多部分格式很简单; 可以在HTML 4.01规范中找到简要介绍.你需要提出一个边界,这是一个在内容中找不到的字符串,比方说HereGoes.您设置了请求标头Content-Type: multipart/form-data; boundary=HereGoes.那么这应该是一个有效的请求体:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--
Run Code Online (Sandbox Code Playgroud)

  • @andig我不知道.也许您可以使用[UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier),但这不一定是个好主意.通常,您的HTTP库应该为您处理. (2认同)
  • 为什么要使用 base64 来编码 JPEG 数据?HTTP 允许您发送原始字节。 (2认同)