java - 发布文件休息模板

标签 java xml spring rest spring-mvc

我正在尝试通过休息调用发布文件。我要 POST 的文件是一个 xml 文件。我还需要在 header 中包含数据以用于授权目的。通过一些挖掘,看起来我应该将这些 header 和文件放入映射中,该映射可以传递给其余模板的交换方法。这是我的源代码

public class BaseTest {
    private RestTemplate restTemplate;
    private HttpHeaders headers;
    private HttpEntity<String> httpEntity;
    private ResponseEntity<String> statusResponse;

    @Before
    public void setUp() {
        restTemplate = new RestTemplate();
        headers = new HttpHeaders();
        headers.set("requester", "test");
        headers.set("Authorization", "Token KqY+VEP3A/Cj");

    @Test
    public void testPost() {
        getHeaders().setContentType(MediaType.APPLICATION_XML);
        setHttpEntity(new HttpEntity(getHeaders() ));

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("file", new FileSystemResource("C:\\Users\\dt208672\\Desktop\\2104000573.SIM2015060000000000.STMT.980061281_52.xml"));
        try {
            getRestTemplate().exchange("https://test.com/documents", HttpMethod.POST, new HttpEntity<MultiValueMap<String, Object>>(map, getHeaders()), String.class);
        }catch(HttpClientErrorException e) {
            fail("Document not found! Status code " + e.getStatusCode());
        }
    }
}

但是,我收到以下错误。不确定该错误意味着什么。我认为我应该将内容类型设置为 application/xml 文件,因为它是一个 xml 文件,但不确定是否需要其他配置。有什么建议吗?

org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [application/xml]
    at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:810)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:594)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
    at com.digitalplatform.test.DocumentTest.testPost(DocumentTest.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

编辑于 2016 年 3 月 16 日晚上 9:20(太平洋标准时间): 其实终点是这样的。这是否意味着我必须改变方法?我可能想避免更改方法中的任何代码..

@RequestMapping(value = "/documents", method = RequestMethod.POST, produces = {
        MediaType.APPLICATION_XML_VALUE, AppConstant.APPLICATION_PDF })
@ResponseStatus(HttpStatus.CREATED)
@AuditEventAccess(auditEventAccessSuccess = AppConstant.AUDIT_EVENT_CLASFN_ID_POST_REALTIME_DOCUMENT_SUCCESSFUL, auditEventAccessError = AppConstant.AUDIT_EVENT_CLASFN_ID_POST_REALTIME_DOCUMENT_FAILED)
public <T> T postRealTimeDocument(final HttpServletRequest request) {

最佳答案

听到的问题是您正在发布一个文件,而不是 xml 格式的字符串。因此,您应该将调用作为 multipart/form-data。

实际上,您的方法应该如下所示

public class BaseTest {

// as your test
    ....

    @Test
    public void testPost() {
        getHeaders().setContentType(MediaType.MULTIPART_FORM_DATA);
        setHttpEntity(new HttpEntity(getHeaders() ));

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("file", new FileSystemResource("C:\\Users\\dt208672\\Desktop\\2104000573.SIM2015060000000000.STMT.980061281_52.xml"));
        try {
            getRestTemplate().exchange("https://test.com/documents", HttpMethod.POST, new HttpEntity<MultiValueMap<String, Object>>(map, getHeaders()), String.class);
        }catch(HttpClientErrorException e) {
            fail("Document not found! Status code " + e.getStatusCode());
        }
    }
}

导致 400 错误的原因是您的客户端执行了多部分请求,但您的端点未为此提案进行配置 每次我跟踪文件时,我都会使用这样的端点:

使用 Apache Commons FileUpload

  @RequestMapping(value = "/documents", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponseEntity saveDocument(@RequestParam("file") MultipartFile file){
       ...
    }

或使用 Servlet 3 抽象

 @RequestMapping(value = "/documents", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponseEntity saveDocument(@RequestParam("file") Part file){
       ...
    }

或者使用 dto 方法

@RequestMapping(value = "/documents", method = RequestMethod.POST, consumes = "multipart/form-data")
    public ResponseEntity saveSocument(@ModelAttribute("file") FileDTO file){
       ...
    }

@Data
class FileDTO {

    private MultipartFile file;
        // eventualy other proeprties

    ....
}

即使您使用标准的 MultipartFile Spring 抽象,Servlet 3 Part 抽象也可以使用像 FileDTO 这样的 dto,关键点是:使用 multipart/form-data 作为消费者媒体类型,具有 Apache commons fileupload 或 servlet 3 环境

希望tihi能帮到你

关于java - 发布文件休息模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36044354/

相关文章:

java - 返回普通模型和 View 与返回重定向模型和 View 之间的区别

java - 是否有一个基于 microsoft-clr 的架构相当于 java-osgi 模块化架构?

hibernate - 在 postgres db 中使用 hibernate-spring 插入记录。序列生成器问题

xml - 带外部文件的 dart xml

java - 如何在 Spring 中保留静态类变量的值?

java - Spring MVC : Expire privilege flag after 5 minutes for edit

java - 快速文本搜索

java - JavaFx 中 3d 框的定位

java - Jackson 没有大写 XML 元素

c# - 使用 tabhost : Xamarin Android 中的每个选项卡设置 axml 布局