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

标签 java spring spring-boot multipartform-data

我在构建一个 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/

相关文章:

java - 记录已执行的 java 代码的行号

spring - 如何在 Spring Boot 中添加 thymeleaf 方言?

java - Spring Boot使用http请求头进行分页

spring - Spring JPA 中的延迟获取 - cron 和 REST 请求中的不同行为

java - GUI构建错误

java - 在变量中存储大量数字的正确方法

java - Ojalgo:在 Java 中定义矩阵是否稳定

spring - Spring Initializr 生成的 pom.xml 出错

Spring XML 命名空间 : How do I find what are the implementing classes behind them?

java - 在 JBOSS EAP 6.1 上部署 spring boot