Exemple #1
0
 private Image getAvatar() {
   HttpConnection httemp = null;
   InputStream istemp = null;
   Image avatar = null;
   try {
     httemp = (HttpConnection) Connector.open(url);
     if (HttpConnection.HTTP_OK != httemp.getResponseCode()) {
       throw new IOException();
     }
     istemp = httemp.openInputStream();
     byte[] avatarBytes = read(istemp, (int) httemp.getLength());
     // #sijapp cond.if modules_TRAFFIC is "true" #
     Traffic.getInstance().addInTraffic(avatarBytes.length);
     // #sijapp cond.end#
     avatar = javax.microedition.lcdui.Image.createImage(avatarBytes, 0, avatarBytes.length);
     avatarBytes = null;
   } catch (Exception e) {
   }
   try {
     httemp.close();
     istemp.close();
   } catch (Exception e) {
   }
   return avatar;
 }
Exemple #2
0
 private Object request(
     String url, boolean post, Hashtable params, boolean basicAuth, boolean processOutput)
     throws Exception {
   HttpConnection conn = null;
   Writer writer = null;
   InputStream is = null;
   try {
     if (!post && (params != null)) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       OutputStreamWriter osw = new OutputStreamWriter(baos, this.encoding);
       this.encodeParams(params, osw);
       osw.flush();
       osw.close();
       osw = null;
       url += "?" + new String(baos.toByteArray(), this.encoding);
       baos = null;
     }
     conn = (HttpConnection) Connector.open(url);
     conn.setRequestMethod(post ? HttpConnection.POST : HttpConnection.GET);
     if (basicAuth) {
       if (!this.areCredentialsSet()) throw new Exception("Credentials are not set");
       String token = base64Encode((this.user + ":" + this.pass).getBytes(this.encoding));
       conn.setRequestProperty("Authorization", "Basic " + token);
     }
     if (post && (params != null)) {
       OutputStream os = conn.openOutputStream();
       writer = new OutputStreamWriter(os, this.encoding);
       this.encodeParams(params, writer);
       writer.flush();
       writer.close();
       os = null;
       writer = null;
     }
     int code = conn.getResponseCode();
     if ((code != 200) && (code != 302))
       throw new Exception("Unexpected response code " + code + ": " + conn.getResponseMessage());
     is = conn.openInputStream();
     if (processOutput) {
       synchronized (this.json) {
         return this.json.parse(is);
       }
     } else {
       this.pump(is, System.out, 1024);
       return null;
     }
   } finally {
     if (writer != null) writer.close();
     if (is != null) is.close();
     if (conn != null) conn.close();
   }
 }
Exemple #3
0
  private String getContent(String url) {
    HttpConnection httemp = null;
    InputStream istemp = null;
    String content = "";

    try {
      httemp = (HttpConnection) Connector.open(url);
      httemp.setRequestProperty("Connection", "cl" + "ose");
      if (HttpConnection.HTTP_OK != httemp.getResponseCode()) {
        throw new IOException();
      }

      istemp = httemp.openInputStream();
      int length = (int) httemp.getLength();
      if (-1 != length) {
        byte[] bytes = new byte[length];
        istemp.read(bytes);
        content = new String(bytes);

      } else {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        while (true) {
          int ch = istemp.read();
          if (-1 == ch) break;
          bytes.write(ch);
        }
        content = new String(bytes.toByteArray());
        bytes.close();
      }

    } catch (Exception e) {
      content = "Error: " + e.getMessage();
    }
    try {
      httemp.close();
      istemp.close();
    } catch (Exception e) {
    }
    return StringConvertor.removeCr(content);
  }
Exemple #4
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();
    }
  }
  /**
   * READ
   *
   * @param url
   * @return
   * @throws IOException
   */
  public String get(String url) throws IOException {
    HttpConnection hcon = null;
    DataInputStream dis = null;
    StringBuffer responseMessage = new StringBuffer();

    try {
      int redirectTimes = 0;
      boolean redirect;

      do {
        redirect = false;

        // a standard HttpConnection with READ access
        hcon = getConnection(url);
        // obtain a DataInputStream from the HttpConnection
        dis = new DataInputStream(hcon.openInputStream());
        // retrieve the response from the server
        int ch;
        while ((ch = dis.read()) != -1) {
          responseMessage.append((char) ch);
        } // end while ( ( ch = dis.read() ) != -1 )
        // check status code
        int status = hcon.getResponseCode();

        switch (status) {
          case HttpConnection.HTTP_OK: // Success!
            break;
          case HttpConnection.HTTP_TEMP_REDIRECT:
          case HttpConnection.HTTP_MOVED_TEMP:
          case HttpConnection.HTTP_MOVED_PERM:
            // Redirect: get the new location
            url = hcon.getHeaderField("location");
            System.out.println("Redirect: " + url);

            if (dis != null) dis.close();
            if (hcon != null) hcon.close();

            hcon = null;
            redirectTimes++;
            redirect = true;
            break;
          default:
            // Error: throw exception
            hcon.close();
            throw new IOException("Response status not OK:" + status);
        }

        // max 5 redirects
      } while (redirect == true && redirectTimes < 5);

      if (redirectTimes == 5) {
        throw new IOException("Too much redirects");
      }

    } catch (Exception e) {
      e.printStackTrace();
      // TODO bad style
      responseMessage.append("ERROR: ");
    } finally {
      try {
        if (hcon != null) hcon.close();
        if (dis != null) dis.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      } // end try/catch
    } // end try/catch/finally
    return responseMessage.toString();
  } // end sendGetRequest( String )
  /**
   * UPDATE
   *
   * @param url
   * @param data the request body
   * @throws IOException
   */
  public String post(String url, String data) throws IOException {

    HttpConnection hcon = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;
    StringBuffer responseMessage = new StringBuffer();

    try {
      int redirectTimes = 0;
      boolean redirect;

      do {
        redirect = false;
        // an HttpConnection with both read and write access
        hcon = getConnection(url, Connector.READ_WRITE);
        // set the request method to POST
        hcon.setRequestMethod(HttpConnection.POST);
        // overwrite content type to be form based
        hcon.setRequestProperty("Content-Type", "application/json");
        // set message length
        if (data != null) {
          hcon.setRequestProperty("Content-Length", "" + data.length());
        }

        if (data != null) {
          // obtain DataOutputStream for sending the request string
          dos = hcon.openDataOutputStream();
          byte[] request_body = data.getBytes();
          // send request string to server
          for (int i = 0; i < request_body.length; i++) {
            dos.writeByte(request_body[i]);
          } // end for( int i = 0; i < request_body.length; i++ )
          dos.flush(); // Including this line may produce
          // undesiredresults on certain devices
        }

        // obtain DataInputStream for receiving server response
        dis = new DataInputStream(hcon.openInputStream());
        // retrieve the response from server
        int ch;
        while ((ch = dis.read()) != -1) {
          responseMessage.append((char) ch);
        } // end while( ( ch = dis.read() ) != -1 ) {
        // check status code
        int status = hcon.getResponseCode();
        switch (status) {
          case HttpConnection.HTTP_OK: // Success!
            break;
          case HttpConnection.HTTP_TEMP_REDIRECT:
          case HttpConnection.HTTP_MOVED_TEMP:
          case HttpConnection.HTTP_MOVED_PERM:
            // Redirect: get the new location
            url = hcon.getHeaderField("location");
            System.out.println("Redirect: " + url);

            if (dis != null) dis.close();
            if (hcon != null) hcon.close();
            hcon = null;
            redirectTimes++;
            redirect = true;
            break;
          default:
            // Error: throw exception
            hcon.close();
            throw new IOException("Response status not OK:" + status);
        }

        // max 5 redirects
      } while (redirect == true && redirectTimes < 5);

      if (redirectTimes == 5) {
        throw new IOException("Too much redirects");
      }
    } catch (Exception e) {
      e.printStackTrace();
      responseMessage.append("ERROR");
    } finally {
      // free up i/o streams and http connection
      try {
        if (hcon != null) hcon.close();
        if (dis != null) dis.close();
        if (dos != null) dos.close();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      } // end try/catch
    } // end try/catch/finally
    return responseMessage.toString();
  }