Spring Rest WebServices返回具有application / json content-type的multipart / form-data

krk*_*rku 4 java spring web-services multipartform-data spring-boot

我在构建一个响应为包含应用程序/ json内容的multipart / form-data的api时遇到问题

例:

http://localhost:8080/getData 
Run Code Online (Sandbox Code Playgroud)

应该回来

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

[{"name":"xyz"}]
--HaRZrgSMRFElYDqkcBMfTMp3BUMHKQAtP--
Run Code Online (Sandbox Code Playgroud)

当前代码段是

@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;   
}
Run Code Online (Sandbox Code Playgroud)

我得到的响应是{}一个空的json对象。有人可以让我知道我要去哪里了吗

krk*_*rku 6

我已经找到解决方案,将其发布,这样对其他人可能会有帮助

@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);
}
Run Code Online (Sandbox Code Playgroud)

响应

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

[{"sample": "sample"}]
--57XYHIgdIhRSOYu6TZA-ybSppMuAtcN3--
Run Code Online (Sandbox Code Playgroud)