处理HttpClient响应的最佳方法

时间:2017-03-31 18:19:08

标签: java string memory-management apache-commons-httpclient

我的HTTP Servlet中有以下方法。基本上它是一个简单的Java servlet,充当代理。浏览器向servlet请求XML数据,servlet打开连接以获取XML数据,并打印响应。根据Apache HttpClient上的docs,不建议使用方法method.getResponseBodyAsString(20000)

  

除非小心使用,否则很容易导致内存不足,因为它们意味着在内存中缓冲整个实体。

所以我试图以鼓励的方式做到这一点,但我不确定this solution是否真的更好。 我的问题是下面显示的响应的处理是否也意味着缓冲整个实体,因为在while循环之后,StringBuilder,xmlResponse,还是整个实体都在内存中?响应是分页的,可能少于10,000个字符。

private void submitHTTPQuery(String searchStr)  {
  HttpClient client = new HttpClient();
  GetMethod method = new GetMethod(searchStr);
  BufferedReader reader = null;
  method.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  int statusCode = 0;
  try {
    client.getHostConfiguration();
    statusCode = client.executeMethod(method);
    if (statusCode == HttpStatus.SC_OK) {

//Discouraged methods
// byte[] responseBody = method.getResponseBody();
// String responseString = method.getResponseBodyAsString(20000);

    reader = new BufferedReader( new InputStreamReader(
      method.getResponseBodyAsStream(), method.getResponseCharSet()));

    StringBuilder result = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
            result.append(line);
    } 
    xmlResponse = result;

    }
} catch (HttpException e) {
    logger.error("Search Servlet HTTP Error",e);
} catch (IOException e) {
    logger.error("Search Servlet IO Error",e);
} finally {
    method.releaseConnection();

    try {
        if(reader !=null ){
            reader.close();
        }

    } catch (IOException e) {
        logger.error("failed to close GSA Search Reader", e);
    }

}

}

http://hc.apache.org/httpclient-3.x/performance.html https://www.mkyong.com/java/apache-httpclient-examples/

0 个答案:

没有答案