gpt4 book ai didi

java - SpringBoot WebService客户端: MultipartFile and String parameters

转载 作者:行者123 更新时间:2023-12-02 11:04:06 25 4
gpt4 key购买 nike

我使用 SpringBoot 实现了上传 REST Web 服务,它接收 2 个参数:

  • 字符串消息
  • 一个文件

Web 服务代码如下所示:

@RequestMapping(value = "/uploadtest", consumes = { MediaType.MULTIPART_FORM_DATA}, method = RequestMethod.POST)
public ResponseEntity<Map<String, String>> upload(
@RequestParam("msg") String msg,
@RequestParam("file") MultipartFile file) {

System.out.println("uploadtest");
return new ResponseEntity<>(singletonMap("url", "uploadtest"), HttpStatus.CREATED);

}

我正在尝试创建 Jersey WS 客户端。当 WS 仅接收 MultipartFile 参数时,以下代码可以正常工作:

Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class).build();
WebTarget webTarget
= client.target("http://localhost:8080/uploadtest");

MultiPart multiPart = new MultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
new File("/filename.xml"),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
multiPart.bodyPart(fileDataBodyPart);

Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multiPart, multiPart.getMediaType()));

此外,如果两个参数都是字符串,则以下代码也有效:

Client client = ClientBuilder.newClient(clientConfig);
WebTarget webTarget
= client.target("http://localhost:8080/uploadtest");

MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("msg", "msg1");
formData.add("mesgbis", "msg2");

String responseResult = webTarget.request()
.post(Entity.entity(formData, MediaType.MULTIPART_FORM_DATA), String.class);

我想了解是否有办法在 MultiPart 对象上创建 bodyPart 以便创建 String 和 MultipartFile 参数。如果不是,我该如何完成对 WS 的请求?

最佳答案

最后我设法让它工作如下:

Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class).build();
WebTarget webTarget
= client.target("http://localhost:8080/uploadtest");

MultiPart multiPart = new MultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
new File("/filename.xml"),
MediaType.APPLICATION_OCTET_STREAM_TYPE);

FormDataBodyPart bodyPartMsg = new FormDataBodyPart("msg", "custom msg");
multiPart.bodyPart(bodyPartMsg);
multiPart.bodyPart(fileDataBodyPart);

Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multiPart, multiPart.getMediaType()));

关于java - SpringBoot WebService客户端: MultipartFile and String parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com