Esempio n. 1
0
  /** Requests an HTTP resource and returns its response as a string */
  public static String request(String httpUrl, Transaction tx) throws IOException {
    checkTransaction(tx);

    DataBuffer buffer = new DataBuffer(256, false);
    InputStream is = null;
    Connection conn = null;
    try {
      // append connection suffix
      httpUrl += getConnectionSuffix();
      Logger.log("Opening URL: " + httpUrl);
      conn = Connector.open(httpUrl);
      tx.setNetworkOperation(conn, is);
      if (conn instanceof HttpConnection) {
        HttpConnection httpConn = (HttpConnection) conn;
        int responseCode = httpConn.getResponseCode();
        is = httpConn.openInputStream();
        tx.setNetworkOperation(conn, is);
        int length = is.read(buffer.getArray());
        buffer.setLength(length);

        String response =
            new String(buffer.getArray(), buffer.getArrayStart(), buffer.getArrayLength());
        if (responseCode == 200) {
          Logger.log("HTTP response: " + response);
          return response;
        } else {
          Logger.warn("HTTP error response: " + response);
          throw new IOException("Http error: " + responseCode + ", " + response);
        }
      } else {
        throw new IOException("Can not make HTTP connection for URL '" + httpUrl + "'");
      }
    } finally {
      PushUtils.close(conn, is, null);
      tx.clearNetworkOperation();
    }
  }