我们使用 HTTPClient 来实现 REST API。
我们正在使用以下方式读取服务器响应:
method = new PostMethod(url);
HttpClient client = new HttpClient();
int statusCode = client.executeMethod(method);
String responseBody = method.getResponseBodyAsString();
当我们这样做时,我们会收到这个警告:
Dec 9, 2009 7:41:11 PM org.apache.commons.httpclient.HttpMethodBase getResponseBody
WARNING: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
docs继续说:
HttpClient is capable of efficient request/response body streaming. Large entities may be submitted or received without being buffered in memory. This is especially critical if multiple HTTP methods may be executed concurrently. While there are convenience methods to deal with entities such as strings or byte arrays, their use is discouraged. Unless used carefully they can easily lead to out of memory conditions, since they imply buffering of the complete entity in memory.
所以我的问题是,如果您确实需要作为字符串的完整响应(即:存储在数据库中,或使用 DOM 进行解析),为什么使用流的内存效率更高?
最佳答案
使用流比将整个实体作为字符串更有效,因为后者意味着
- 在返回到您的代码之前需要阅读响应的全部内容,并且
- 在服务器发送完整的响应之前,无法将控制权返回给您的代码。
如果您将响应作为流处理,那么您实际做的是一次处理 N 个字节。这意味着您可以在远程服务器仍在发回下一个数据段时开始处理第一个响应段。因此,如果您的用例允许您处理收到的数据,这作为一种访问方法更有意义。
但是,如果您出于某种原因需要整个响应作为字符串,那么流方法的所有效率对您都没有任何影响——因为即使您分段读取响应,您仍然需要等待整个响应 - 并将其全部包含在一个字符串中 - 然后才能处理它。
只有当您有这样一个用例,您可以在拥有整个响应正文之前开始处理响应时,使用流的效率才对您可用。
关于java - 为什么将输入读取为流与字符串相比内存效率更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877979/