RestTemplate postForObject响应被截断

时间:2016-09-23 16:28:15

标签: string spring resttemplate

尝试使用spring Web客户端获取响应,但结果响应因为响应大小超过字符串类而被截断。有没有其他方法来获得响应而不被截断?

LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
        //String response = "";
        try{
            File tempFile = File.createTempFile("ccda", "File");
            FileOutputStream out = new FileOutputStream(tempFile);
            IOUtils.copy(ccdaFile.getInputStream(), out);
            requestMap.add("ccdaFile", new FileSystemResource(tempFile));       
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = 
                                        new HttpEntity<LinkedMultiValueMap<String, Object>>(requestMap, headers);
            RestTemplate restTemplate = new RestTemplate();
            FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
            formConverter.setCharset(Charset.forName("UTF8"));
            restTemplate.getMessageConverters().add(formConverter);
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            String response = restTemplate.postForObject("localhost:8080", 
                                                requestEntity, String.class);

            tempFile.delete();
        }catch(Exception exc)
        {
            exc.printStackTrace();
        }

1 个答案:

答案 0 :(得分:0)

您可以使用InputStream 我想你可以这样做:

InputStream is = rt.execute("localhost:8080", HttpMethod.POST, requestCallback, responseExtractor);

其中requestCallback是org.springframework.web.client.RequestCallback的实现,就像这个

public class MyRequestCallback implements RequestCallback
{
    @Override
    public void doWithRequest(ClientHttpRequest request) throws IOException
    {
        request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE);
        request.getHeaders().add(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_JSON_VALUE);
    }
}

虽然responseExtractor可能是由这个类的实例

public class MyResponseExtractor implements ResponseExtractor<InputStream>
{
    @Override
    public Boolean extractData(ClientHttpResponse response) throws IOException
    {
        HttpStatus status = response.getStatusCode();
        switch (status)
        {
        case OK:
            return response.getBody();
        default:
            return null;
        }   
    }
}

一旦获得InputStream,您就可以管理它 希望它有用