HttpClients.java 2.3 KB
Newer Older
E
Eric Burke 已提交
1 2 3 4 5 6 7
// Copyright 2010 Square, Inc.
package retrofit.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
8 9 10 11
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.entity.ByteArrayEntity;
E
Eric Burke 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

/**
 * Utility methods for dealing with HttpClient.
 *
 * @author Bob Lee (bob@squareup.com)
 */
public class HttpClients {
  private static final Logger logger =
      Logger.getLogger(HttpClients.class.getName());

  /**
   * Converts an HttpEntity to a byte[].
   *
   * @throws NullPointerException if the entity is null
   */
  public static byte[] entityToBytes(HttpEntity entity) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    entity.writeTo(bout);
    return bout.toByteArray();
  }

  /**
   * Converts an HTTP response to an IOException.
   */
  public static IOException responseToException(HttpResponse response) {
    StatusLine statusLine = response.getStatusLine();
    String body = null;
    try {
      // TODO: Ensure entity is text-based and specify encoding.
      HttpEntity entity = response.getEntity();
      if (entity != null) body = new String(entityToBytes(entity));
    } catch (Throwable t) {
      // The original error takes precedence.
      logger.log(Level.WARNING, "Response entity to String conversion.", t);
    }
    return new IOException("Unexpected response."
        + " Code: " + statusLine.getStatusCode()
        + ", Reason: " + statusLine.getReasonPhrase()
        + ", Body: " + body);
  }

  /**
   * Copies a response (so we can read it a second time) and logs it.
   */
  public static HttpEntity copyAndLog(HttpEntity entity) throws IOException {
    byte[] bytes = entityToBytes(entity);
    // TODO: Use correct encoding.
P
Patrick Forhan 已提交
59 60 61 62 63 64 65 66 67 68 69
    if (logger.isLoggable(Level.FINE)) {
      final int chunkSize = 4000;
      logger.fine("-Response:");
      for (int i = 0; i < bytes.length; i += chunkSize) {
        int end = i + chunkSize;
        logger.fine(((end > bytes.length) ? new String(bytes, i, bytes.length - i)
                                          : new String(bytes, i, chunkSize)));
      }
      logger.fine("-end response.");
    }

E
Eric Burke 已提交
70 71 72
    return new ByteArrayEntity(bytes);
  }
}