首页 > 解决方案 > Content-Length 分隔的消息正文过早结束 - Resttemplate

问题描述

我正在使用 Spring RestTemplate 从第三方 URL 下载一个大文件。我使用以下方法下载文件,以免将整个文件加载到内存中。


// Optional Accept header
RequestCallback requestCallback = request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

// Streams the response instead of loading it all in memory
ResponseExtractor<Void> responseExtractor = response -> {
    // Here I write the response to a file but do what you like
    Path path = Paths.get("some/path");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor

这很好用,但是我们间歇性地得到一个Premature end of Content-Length delimited message body

我从另一个堆栈溢出帖子中读到这是一个服务器端问题。如何确定这是服务器端问题?我如何知道这是第三方方面的内存问题还是响应标头中的内容长度不正确等?在我向第三方寻求解决方案之前,我需要确认一下。

标签: javaspring-boothttpresttemplatehttp-content-length

解决方案


根据触发错误的难易程度,您可以使用诸如curl调用 URL 之类的工具(仅用于测试,在您的应用程序之外)。如果还是看到失败,那肯定不是客户端的问题,因为那些知名的第三方工具都经过了很好的测试,没有这样的bug。


推荐阅读