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
 public static void debugConnection(HttpConnection hc) {
   debug("network", "Request Method for this connection is " + hc.getRequestMethod());
   debug("network", "URL in this connection is " + hc.getURL());
   debug("network", "Protocol for this connection is " + hc.getProtocol()); // It better be HTTP:)
   debug("network", "This object is connected to " + hc.getHost() + " host");
   debug("network", "HTTP Port in use is " + hc.getPort());
   debug("network", "Query parameter in this request are  " + hc.getQuery());
   debug("network", "Length " + hc.getLength());
 }
  /**
   * Method to configure the HTTP response stream. This method will do whatever mechanics are
   * necessary to utilize the HTTP connection object to return an input stream to the HTTP response.
   *
   * @param http the HttpConnection object, already opened and presumably with response data waiting
   * @return an InputStream corresponding to the response data from this HttpConnection or null if
   *     not available.
   */
  protected InputStream setupResStream(HttpConnection http) throws IOException, ServerException {
    int response = http.getResponseCode();

    if (response == HttpConnection.HTTP_MOVED_PERM || response == HttpConnection.HTTP_MOVED_TEMP) {
      // Resource was moved, get a new location and retry the operation
      String newLocation = http.getHeaderField("Location");
      setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, newLocation);
      resourceMoved = true;
      return null;
    }

    InputStream input = http.openInputStream();

    if (response == HttpConnection.HTTP_OK) {

      // Catch any session cookie if one was set
      String useSession = getProperty(Stub.SESSION_MAINTAIN_PROPERTY);
      if (useSession != null && useSession.toLowerCase().equals("true")) {
        String cookie = http.getHeaderField("Set-Cookie");
        if (cookie != null) {
          addSessionCookie(getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY), cookie);
        }
      }

      return input;
    } else {
      Object detail =
          decoder.decodeFault(faultHandler, input, http.getEncoding(), http.getLength());

      if (detail instanceof String) {
        if (((String) detail).indexOf("DataEncodingUnknown") != -1) {
          throw new MarshalException((String) detail);
        } else {
          throw new ServerException((String) detail);
        }
      } else {
        Object[] wrapper = (Object[]) detail;
        String message = (String) wrapper[0];
        QName name = (QName) wrapper[1];
        detail = wrapper[2];
        throw new JAXRPCException(message, new FaultDetailException(name, detail));
      }
    }
  }
Exemple #4
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);
  }
  private String postViaHttpConnection(String url, byte[] b) throws IOException {
    HttpConnection c = null;
    InputStream is = null;
    OutputStream os = null;
    int rc;

    try {
      c = (HttpConnection) Connector.open(url);

      // Set the request method and headers
      c.setRequestMethod(HttpConnection.POST);

      c.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT");
      c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

      c.setRequestProperty("Content-Language", "en-US");

      // Getting the output stream may flush the headers
      os = c.openOutputStream();
      os.write(b);
      os.flush(); // Optional, getResponseCode will flush

      // Getting the response code will open the connection,
      // send the request, and read the HTTP response headers.
      // The headers are stored until requested.
      rc = c.getResponseCode();

      if (rc != HttpConnection.HTTP_OK) {
        throw new IOException("HTTP response code: " + rc);
      }

      is = c.openInputStream();

      // Get the ContentType
      String type = c.getType();
      // processType(type);

      // Get the length and process the data
      int len = (int) c.getLength();
      if (len > 0) {
        int actual = 0;
        int bytesread = 0;
        byte[] data = new byte[len];
        while ((bytesread != len) && (actual != -1)) {
          actual = is.read(data, bytesread, len - bytesread);
          bytesread += actual;
        }
        String s = "";
        for (int i = 0; i < data.length; i++) {
          s = s + (char) data[i];
        }
        return s;
      }
      // else {
      // int ch;
      // while ((ch = is.read()) != -1) {
      // process((byte)ch);
      // }
      // }

    } catch (ClassCastException e) {
      throw new IllegalArgumentException("Not an HTTP URL");
    } finally {
      if (is != null) is.close();
      if (os != null) os.close();
      if (c != null) c.close();
    }

    return "Resp"; //
  }
  private synchronized void httpPostRequest(String postData) throws IOException {
    try {
      HttpConnection hc = (HttpConnection) Connector.open(pollingUrl);
      hc.setRequestMethod(HttpConnection.POST);
      hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      hc.setRequestProperty("Host", "host");

      StringBuffer out = new StringBuffer();
      if (sessionId == null) {
        out.append("0");
        keys = new Vector();
      } else out.append(sessionId);

      do {
        if (keys.size() == 0) {
          initKeys();
        }
        out.append(";").append((String) keys.lastElement());
        keys.removeElementAt(keys.size() - 1);
      } while (keys.size() == 0);

      out.append(",").append(postData);

      int outLen = out.length();
      // hc.setRequestProperty("Content-Length", String.valueOf(outLen));

      byte bytes[] = new byte[outLen];
      for (int i = 0; i < outLen; i++) {
        bytes[i] = (byte) out.charAt(i);
      }

      OutputStream os = hc.openOutputStream();
      os.write(bytes);
      os.close();

      int resp = hc.getResponseCode();

      if (resp != HttpConnection.HTTP_OK) throw new IOException("HTTP Error code" + resp);

      InputStream is = hc.openInputStream();

      String cookie = hc.getHeaderField("Set-Cookie");
      int expires = cookie.indexOf(';');
      if (expires > 0) cookie = cookie.substring(3, expires);

      if (cookie.endsWith(":0")) {
        opened = false;
        error = cookie;
      }

      if (sessionId == null) {
        sessionId = cookie;
      }

      byte data[];
      int inLen = (int) hc.getLength();

      if (inLen < 0) {
        throw new Exception("Content-Length missing"); // TODO:
      } else {
        int actual = 0;
        int bytesread = 0;
        data = new byte[inLen];
        while ((bytesread != inLen) && (actual != -1)) {
          actual = is.read(data, bytesread, inLen - bytesread);
          bytesread += actual;
        }

        if (inLen > 0) inStack.addElement(data);
      }
      is.close();
      hc.close();
    } catch (Exception e) {
      opened = false;
      error = e.toString();
      // #ifdef DEBUG
      // #             e.printStackTrace();
      // #endif
    }
  }
  /**
   * Invokes the wsdl:operation defined by this <code>Operation</code> and returns the result.
   *
   * @param params a <code>ValueType</code> array representing the input parameters for this <code>
   *     Operation</code>. Can be <code>null</code> if this operation takes no parameters.
   * @return a <code>ValueType</code> array representing the output value(s) for this operation. Can
   *     be <code>null</code> if this operation returns no value.
   * @throws JAXRPCException
   *     <UL>
   *       <LI>if an error occurs while excuting the operation.
   *     </UL>
   *
   * @see javax.microedition.xml.rpc.Operation
   */
  public Object invoke(Object params) throws JAXRPCException {
    HttpConnection http = null;
    OutputStream ostream = null;
    InputStream istream = null;
    Object result = null;
    int attempts = 0;
    // Maximal number of "Object moved" http responses that we will handle
    final int maxAttempts = 10; // Constants.MAX_REDIRECT_ATTEMPTS;

    try {
      do {
        // This flag will be set to 'true' by setupResStream() method
        // if code 3xx is returned by the http connection.
        resourceMoved = false;

        // open stream to service endpoint
        http = (HttpConnection) Connector.open(getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY));

        ostream = setupReqStream(http);

        // IMPL NOTE: encoding should be either UTF-8 or UTF-16
        encoder.encode(params, inputType, ostream, null);

        if (ostream != null) {
          ostream.close();
        }

        istream = setupResStream(http);

        if (returnType != null && istream != null) {
          result = decoder.decode(returnType, istream, http.getEncoding(), http.getLength());
        }

        if (http != null) {
          http.close();
        }
        if (istream != null) {
          istream.close();
        }

      } while (resourceMoved && (attempts++ < maxAttempts));

      if (resourceMoved) {
        throw new JAXRPCException("Too many redirections");
      }

      return result;

    } catch (Throwable t) {
      // Debug Line

      if (ostream != null) {
        try {
          ostream.close();
        } catch (Throwable t2) {
        }
      }
      if (istream != null) {
        try {
          istream.close();
        } catch (Throwable t3) {
        }
      }
      if (http != null) {
        try {
          http.close();
        } catch (Throwable t1) {
        }
      }
      // Re-throw whatever error/exception occurs as a new
      // JAXRPCException
      if (t instanceof JAXRPCException) {
        throw (JAXRPCException) t;
      } else {
        if (t instanceof MarshalException
            || t instanceof ServerException
            || t instanceof FaultDetailException) {
          throw new JAXRPCException(t);
        } else {
          throw new JAXRPCException(t.toString());
        }
      }
    }
  }
  public String ReadRemoteFile() throws IOException {
    HttpConnection hc = null;
    // DataInputStream dis = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    byte[] data = null;
    String sResult = "";
    StringBuffer sb = new StringBuffer();
    int length = 0;

    try {
      // String local_code = ReadLocalCode("expe");
      String local_code = "201101";
      String url = sHttpSchema + sRemoteRoot + sLocalExpePrefix + local_code + sLocalDataExt;
      hc = (HttpConnection) Connector.open(url);
      hc.setRequestMethod(HttpConnection.GET);

      int iResponseCode = hc.getResponseCode();
      if (iResponseCode == HttpConnection.HTTP_OK) {
        is = hc.openInputStream();
        length = (int) hc.getLength();

        if (length != -1) {
          data = new byte[length];
          is.read(data);
          sResult = new String(data);
        } else {
          baos = new ByteArrayOutputStream();
          int ch;
          while ((ch = is.read()) != -1) {
            baos.write(ch);
          }
          sResult = new String(baos.toByteArray());
        }
        System.out.println(sResult);
      } else {
        sResult = "ERROR: NO iResponseCode == HttpConnection.HTTP_OK";
        System.out.println(sResult);
      }

      /*if (length != -1) {
      data = new byte[length];
      dis = new DataInputStream(hc.openInputStream());
      //dis.readFully(data);
      } else {
      SetMessages("ERROR: Content length not given.");
      }*/
      /*int ch;
      while ((ch = is.read()) != -1) {
      sb.append((char) ch);
      }*/

      // sResult = sb.toString();
      // System.out.println(sResult);
    } catch (ConnectionNotFoundException cnfex) {
      SetMessages(cnfex.toString());
      sResult = GetMessages();
      cnfex.printStackTrace();
    } catch (IOException ioex) {
      SetMessages(ioex.toString());
      sResult = GetMessages();
      ioex.printStackTrace();
    } catch (Exception ex) {
      SetMessages(ex.toString());
      sResult = GetMessages();
      ex.printStackTrace();
    } finally {
      if (baos != null) {
        baos.close();
      }

      if (is != null) {
        is.close();
      }

      if (hc != null) {
        hc.close();
      }
    }

    return sResult;
  }
  /**
   * Gets the connection attribute of the CommonDS object
   *
   * @exception IOException Description of the Exception
   */
  void getConnection() throws IOException {
    boolean goodurl = false;

    if (locator == null) {
      throw (new IOException(this + ": connect() failed"));
    }

    contentType = null;
    String fileName = getRemainder(locator);

    if (fileName == null) {
      throw new IOException("bad url");
    }
    int i = fileName.lastIndexOf((int) ('.'));
    if (i != -1) {
      String ext = fileName.substring(i + 1).toLowerCase();
      contentType = Configuration.getConfiguration().ext2Mime(ext);
    }

    if (contentType == null) {
      contentType = "unknown";
    }

    try {
      if (locator.toLowerCase().startsWith("http:")) {
        HttpConnection httpCon = (HttpConnection) Connector.open(locator);
        int rescode = httpCon.getResponseCode();
        // If the response code of HttpConnection is in the range of
        // 4XX and 5XX, that means the connection failed.
        if (rescode >= 400) {
          httpCon.close();
          goodurl = false;
        } else {
          inputStream = httpCon.openInputStream();
          contentLength = httpCon.getLength();
          String ct = httpCon.getType().toLowerCase();
          if (contentType.equals("unknown")) {
            contentType = Configuration.getConfiguration().ext2Mime(ct);
          }
          httpCon.close();
          goodurl = true;
        }
      } else if (locator.startsWith("file:")) {
        // #ifdef USE_FILE_CONNECTION [
        FileConnection fileCon = (FileConnection) Connector.open(locator);
        if (fileCon.exists() && !fileCon.isDirectory() && fileCon.canRead()) {
          inputStream = fileCon.openInputStream();
          contentLength = fileCon.fileSize();
          fileCon.close();
          goodurl = true;
        } else {
          fileCon.close();
          goodurl = false;
        }
        // #else ] [
        // throw new IOException("file protocol isn't supported");
        // #endif ]
      } else if (locator.startsWith("rtp:")) {
        if (contentType.equals("unknown")) contentType = "content.rtp";
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      } else if (locator.startsWith("rtsp:")) {
        if (contentType.equals("unknown")) contentType = "content.rtp";
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      } else if (locator.equals(Manager.TONE_DEVICE_LOCATOR)
      // #ifndef ABB [
      // || locator.equals(Manager.MIDI_DEVICE_LOCATOR)
      // #endif ]
      ) {
        inputStream = null;
        contentLength = -1;
        goodurl = true;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new IOException("failed to connect: " + ex.getMessage());
    }

    if (!goodurl) throw new IOException("bad url");
  }
 public long getLength() {
   return httpConnection.getLength();
 }
  String postRequest(String url) {
    HttpConnection hc = null;
    DataInputStream in = null;
    OutputStream os = null;
    try {

      hc = (HttpConnection) Connector.open(url);
      hc.setRequestMethod(HttpConnection.POST);
      hc.setRequestProperty("username", "bng");
      hc.setRequestProperty("password", "123456");
      os = hc.openDataOutputStream();
      JSONObject jSONObject = new JSONObject();
      jSONObject.put("start_count", 1);
      jSONObject.put("end_count", 10);
      jSONObject.put("type", 1);
      //            os.write("{\"start_count\":\"1\",\"end_count\":\"12\"}".getBytes());
      os.write(jSONObject.toString().getBytes());
      // Always get the Response code first .
      int responseCode = hc.getResponseCode();
      if (responseCode == HttpConnection.HTTP_OK) {
        // You have successfully connected.
        int length = (int) hc.getLength();
        System.out.println("length : " + length);
        byte[] data = null;
        if (length != -1) {
          data = new byte[length];
          in = new DataInputStream(hc.openInputStream());
          in.readFully(data);
        } else {
          // If content length is not given, read in chunks.
          int chunkSize = 512;
          int index = 0;
          int readLength = 0;
          in = new DataInputStream(hc.openInputStream());
          data = new byte[chunkSize];
          do {
            if (data.length < index + chunkSize) {
              byte[] newData = new byte[index + chunkSize];
              System.arraycopy(data, 0, newData, 0, data.length);
              data = newData;
            }
            readLength = in.read(data, index, chunkSize);
            index += readLength;
          } while (readLength == chunkSize);
          length = index;
        }
        return new String(data);
        //                        Image image = Image.createImage(data, 0, length);
        //                        ImageItem imageItem = new ImageItem(null, image, 0, null);
        //                        mForm.append(imageItem);
        //                        mForm.setTitle("Done.");

      } else {
        // Problem with your connection
        Dialog.show(null, "error downloading images", "OK", null);
        return null;
      }
    } catch (Exception e) {
      e.printStackTrace();
      Dialog.show(null, "error downloading images", "OK", null);
      return null;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
      if (os != null) {
        try {
          os.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
      if (hc != null) {
        try {
          hc.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
  }