HttpResponse.java

  1. package gov.usgs.earthquake.aws;

  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;

  6. import javax.json.Json;
  7. import javax.json.JsonObject;

  8. import gov.usgs.util.StreamUtils;

  9. /**
  10.  * Utility class to hold HttpURLConnection and parse JSON response data.
  11.  */
  12. public class HttpResponse {
  13.   /** Variable to hold HttpURLConnection */
  14.   public final HttpURLConnection connection;
  15.   /** Variable for holding IOExceptions */
  16.   public final IOException readException;
  17.   /** Varialbe to hold URL response */
  18.   public final byte[] response;

  19.   /**
  20.    * Reads response from HttpUrlConnection.
  21.    * @param connection HttpURLConnection to read
  22.    * @throws Exception exception if errors
  23.    */
  24.   public HttpResponse(final HttpURLConnection connection) throws Exception {
  25.     this.connection = connection;
  26.     IOException exception = null;
  27.     byte[] data = null;
  28.     try (final InputStream in = connection.getInputStream()) {
  29.       data = StreamUtils.readStream(in);
  30.     } catch (IOException e) {
  31.       exception = e;
  32.       try (final InputStream err = connection.getErrorStream()) {
  33.         data = StreamUtils.readStream(err);
  34.       } catch (IOException e2) {
  35.         // ignore
  36.       }
  37.     } finally {
  38.       this.response = data;
  39.       this.readException = exception;
  40.     }
  41.   }

  42.   /**
  43.    * Parse response into JsonObject.
  44.    *
  45.    * @return parsed JsonObject
  46.    * @throws Exception if unable to parse.
  47.    */
  48.   public JsonObject getJsonObject() throws Exception {
  49.     return Json.createReader(new ByteArrayInputStream(response)).readObject();
  50.   }
  51. }