Как ограничить длину ответа HttpClient - PullRequest
3 голосов
/ 01 апреля 2012

Я использую htmlunit с httpclient.Как я могу ограничить response body length из httpclient, чтобы сказать 1MB?

Ответы [ 2 ]

2 голосов
/ 12 октября 2012

Трюк прост. Вы должны взять InputStream, прочитать из него и прекратить чтение при превышении лимита.

      InputStream instream = method.getResponseBodyAsStream();

Я сделал пример, немного настраивая пример Apache.

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpClientTutorial {

  private static String url = "http://www.apache.com";
  private static final int LIMIT = 1024*1024;//set to 1MB
  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();
    // Create a method instance.
    GetMethod method = new GetMethod(url);   
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));
    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }
      // Read the response body.
      //byte[] responseBody = method.getResponseBody();
      byte[] responseBody = null;    
      InputStream instream = method.getResponseBodyAsStream();
      if (instream != null) {
          long contentLength = method.getResponseContentLength();
          if (contentLength < Integer.MAX_VALUE) { //guard below cast from overflow
              ByteArrayOutputStream outstream = new ByteArrayOutputStream();
              byte[] buffer = new byte[1024];
              int len;
              int total = 0;
              while ((len = instream.read(buffer)) > 0 && total<LIMIT) {
                  outstream.write(buffer, 0, len);
                  total+= len;
              }
              responseBody = outstream.toByteArray();
              outstream.close();
              instream.close();
              System.out.println(new String(responseBody));
          }
      }
    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

Надеюсь, это поможет.

0 голосов
/ 17 февраля 2017

Вы можете использовать BoundedInputStream от Apache Commons. Это поток, который будет поставлять байты только определенной длины - если его позиция превысит это, он остановится.

...