Spring restTemplate execute()POST大文件并获得响应

时间:2015-06-21 00:51:34

标签: java spring rest stream resttemplate

我花了很长时间才研究出来,所以我想分享一下。大多数信息来自SO,我想巩固到这一个地方。

我的要求是使用RESTFul POST上传文件。由于可能是大文件,我想流式传输文件。我显然希望能够阅读回复。

我计划将Jersey用作REST服务器,将Spring的RestTemplate用作客户端(并用于测试)。

我遇到的问题是流式传输和接收响应。我怎样才能做到这一点? (修辞问题 - 我回答这个问题!)

2 个答案:

答案 0 :(得分:7)

没有必要通过RequestCallback来完成所有这些箍。只需使用PathResource

PathResource pathResource = new PathResource(theTestFilePath);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(pathResource), String.class);

Spring将使用ResourceHttpMessageConverter将给定Path标识的文件序列化到请求正文。在内部,Spring 4.x实现使用4096字节的缓冲区大小(这也是IOUtils#copy(..)使用的)。

显然,您可以提供所需的响应类型。上面的示例要求响应正文为String。使用ResponseEntity,您可以使用

访问所有响应标头
HttpHeaders responseHeaders = response.getHeaders();

答案 1 :(得分:1)

我正在使用SpringBoot 1.2.4.RELEASE,而泽西被拉入:

compile("org.springframework.boot:spring-boot-starter-jersey")

我使用精彩的Spring Starter项目(Spring Tool Suite > New创建了项目,或者您可以通过我相信的网站创建,毫无疑问IntelliJ也具备此功能)。并选择泽西岛(JAX-RS)&#39;选项。在gradle build.gradle中,我还添加了依赖项:

compile('commons-io:commons-io:2.4')

我写了这个服务器端代码。

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import org.me.fileStore.service.FileStoreService;

@RestController
@Path("/filestore")
public class FileStoreRestService {
    private static Logger logger = LoggerFactory.getLogger(FileStoreRestService.class);

    @Autowired
    private FileStoreService fileStoreService;


    @POST
    @Path("upload")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    @Produces(MediaType.APPLICATION_JSON)
    public Response Upload(InputStream stream) throws IOException, URISyntaxException { //
        String location = fileStoreService.upload(stream);  // relative path
        URI loc = new URI(location);
        Response response = Response.created(loc).build();
        System.out.println("POST - response: " + response + ", :" + response.getHeaders());
        return response;
    }

我遇到的最大问题是获取某个地点的回复。

首先,我必须处理流媒体大文件。我按照https://stackoverflow.com/a/15785322/1019307进行了操作,如下面的测试所示。无论我根据帖子HttpMessageConverterExtractor尝试了什么,我都没有得到回复:

final HttpMessageConverterExtractor<String> responseExtractor =
new HttpMessageConverterExtractor<String>(String.class, restTemplate.getMessageConverters());

找到https://stackoverflow.com/a/6006147/1019307之后我写道:

private static class ResponseFromHeadersExtractor implements ResponseExtractor<ClientHttpResponse> {

    @Override
    public ClientHttpResponse extractData(ClientHttpResponse response) {
        System.out.println("StringFromHeadersExtractor - response headers: " + response.getHeaders());
        return response;
    }
}

这给了我这个测试:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = FileStoreApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:9000")
public class FileStoreRestServiceTest {
    private static Logger logger = LoggerFactory.getLogger(FileStoreRestServiceTest.class);
    protected final Log logger2 = LogFactory.getLog(getClass());

    String base = "http://localhost:9000/filestore";
    private RestTemplate restTemplate = new TestRestTemplate();

@Test
public void testMyMethodExecute() throws IOException {
    String content = "This is file contents\nWith another line.\n";
    Path theTestFilePath = TestingUtils.getTempPath(content);
    InputStream inputStream = Files.newInputStream(theTestFilePath);

    String url = base + "/upload";
    final RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void doWithRequest(final ClientHttpRequest request) throws IOException {
            request.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);
            IOUtils.copy(inputStream, request.getBody());
        }
    };
    final RestTemplate restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setBufferRequestBody(false);
    restTemplate.setRequestFactory(requestFactory);
    ClientHttpResponse response = restTemplate.execute(url, HttpMethod.POST, requestCallback,
            new ResponseFromHeadersExtractor());
    URI location = response.getHeaders().getLocation();
    System.out.println("Location: " + location);
    Assert.assertNotNull(location);
    Assert.assertNotEquals(0, location.getPath().length());

}

private static class ResponseFromHeadersExtractor implements ResponseExtractor<ClientHttpResponse> {

    @Override
    public ClientHttpResponse extractData(ClientHttpResponse response) {
        System.out.println("StringFromHeadersExtractor - response headers: " + response.getHeaders());
        return response;
    }
}

我需要在该测试中将重点重构为某些服务。