gpt4 book ai didi

java - Spring Rest 返回 multipart/form-data 和 application/json 内容类型

转载 作者:行者123 更新时间:2023-12-02 08:49:47 24 4
gpt4 key购买 nike

我在构建一个 api 时遇到问题,该 API 的响应是带有 application/json 内容的 multipart/form-data

示例:

http://localhost:8080/getData 

应该返回

--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP
Content-Disposition: form-data; name="response"
Content-Type: application/json

[{"name":"xyz"}]
--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP--

当前代码片段是

@RequestMapping(value="/getData", method=RequestMethod.GET, 
produces=MediaType.MULTIPART_FORM_DATA_VALUE)
public MultipartFile getMultipartAsFileAsObject() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("sample.json").getFile());
String readFile = readFile("sample.json");
DiskFileItem fileItem = new DiskFileItem("file", "application/json", false, "response", (int) file.length() , file);
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}

我得到的回应是 {} 一个空的 json 对象。有人可以让我知道我哪里出错了

最佳答案

我已经找到了解决方案,将其发布,以便对其他人有所帮助

@RequestMapping(method = { RequestMethod.GET }, value = "/getData", produces = 
MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> getData() {

s= "[{\"sample\": \"sample\"}]";
JsonArray ja = (new JsonParser()).parse(s).getAsJsonArray();
MultiValueMap<String, Object> mpr = new LinkedMultiValueMap<String, Object>();
HttpHeaders xHeader = new HttpHeaders();
xHeader.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> xPart = new HttpEntity<String>(ja.toString(), xHeader);
mpr.add("response", xPart);
return new ResponseEntity<MultiValueMap<String, Object>>(mpr,
HttpStatus.OK);
}

回应

--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3
Content-Disposition: form-data; name="response"
Content-Type: application/json
Content-Length: 1186

[{"sample": "sample"}]
--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3--

关于java - Spring Rest 返回 multipart/form-data 和 application/json 内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46286939/

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