Package javax.microedition.io

Examples of javax.microedition.io.HttpConnection


      String url = Build.DOWNLOAD_URL;
      String applicationVersion = getApplicationVersion();
      String userAgent = getUserAgent();
      String language = getLanguage();
      for (int redirectCount = 0; redirectCount < 10; redirectCount++) {
        HttpConnection c = null;
        InputStream s = null;
        try {
          c = connect(url);
          c.setRequestMethod(HttpConnection.GET);
          c.setRequestProperty("User-Agent", userAgent);
          c.setRequestProperty("Accept-Language", language);

          int responseCode = c.getResponseCode();
          if (responseCode == HttpConnection.HTTP_MOVED_PERM
              || responseCode == HttpConnection.HTTP_MOVED_TEMP) {
            String location = c.getHeaderField("Location");
            if (location != null) {
              url = location;
              continue;
            } else {
              throw new IOException("Location header missing");
            }
          } else if (responseCode != HttpConnection.HTTP_OK) {
            throw new IOException("Unexpected response code: " + responseCode);
          }
          s = c.openInputStream();
          String enc = getEncoding(c);
          Reader reader = new InputStreamReader(s, enc);
          final String version = getMIDletVersion(reader);
          if (version == null) {
            throw new IOException("MIDlet-Version not found");
          } else if (!version.equals(applicationVersion)) {
            Application application = Application.getApplication();
            application.invokeLater(new Runnable() {
              public void run() {
                mCallback.onUpdate(version);
              }
            });
          } else {
            // Already running latest version
          }
        } finally {
          if (s != null) {
            s.close();
          }
          if (c != null) {
            c.close();
          }
        }
      }
    } catch (Exception e) {
      System.out.println(e);
View Full Code Here


    fc.close();
  }

  public void run() {
    FileConnection fc = null;
    HttpConnection hc = null;
   
    InputStream is = null;
    OutputStream os = null;
   
    boolean isHTTPS = false;
    boolean hasQuery = false;
   
    StringBuffer errorBuffer;
   
    try {
     
      try {
        createFolders(_filePath);
       
                fc = (FileConnection)Connector.open(_filePath, Connector.READ_WRITE);
               
                if (!fc.exists()) {
                  fc.create();
                }
            } catch (Exception e) {
              errorBuffer = new StringBuffer("Unable to create file: ");
              errorBuffer.append(e.getMessage());
             
              Logger.error(errorBuffer.toString());
                callErrorCallback(new String[] { errorBuffer.toString() });
                return;
            }
           
      if (_url.indexOf("https") == 0) {
        isHTTPS = true;
        Logger.error("Setting End to End");
        _factory.setEndToEndDesired(isHTTPS);
      }
     
      hasQuery = (_url.indexOf("?") > -1);
     
      String params = (_params != null) ? getParameters(_params) : ""
     
      if (HttpConnection.GET == _method && params.length() > 0) {
        if (hasQuery) {
          _url += "&" + params;
        } else {
          _url += "?" + params;
        }
      }
           
      ConnectionDescriptor connDesc = _factory.getConnection(_url);
     
      if (connDesc != null) {
        Logger.info("URL: " + connDesc.getUrl());
        try {
          if (isHTTPS) {
            hc = (HttpsConnection) connDesc.getConnection();
          } else {
            hc = (HttpConnection) connDesc.getConnection();
          }   
       
          hc.setRequestMethod(_method);
         
          if (_headers != null) {
            String hKey;
            String hVal;
            for (Enumeration e = _headers.keys(); e.hasMoreElements();) {
              hKey = e.nextElement().toString();
                    hVal = (String) _headers.get(hKey);
                   
                    Logger.error(hKey +": " + hVal);

              hc.setRequestProperty(hKey, hVal);
            }
          }
         
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_USER_AGENT,
                        System.getProperty("browser.useragent"));
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
         
          if (HttpConnection.POST == _method) {
            os = hc.openDataOutputStream();
            os.write(params.getBytes());
          }
               
                is = hc.openDataInputStream();
                int responseCode = hc.getResponseCode();
               
          if (responseCode != HttpConnection.HTTP_OK) {
            Logger.error("Response code: " +responseCode);
            callErrorCallback(new Object[] { "Server Error", new Integer(responseCode) });
          } else {
            byte[] file = IOUtilities.streamToBytes(is);
                  os = fc.openDataOutputStream();
                  os.write(file);
                  os.close();
            callSuccessCallback(new Object[]{ _filePath });
          }
        } catch (Throwable e) {
          callErrorCallback(new String[] { e.getMessage() });
          e.printStackTrace();
        }
      } else {
        Logger.error("Error creating HTTP connection");
        callErrorCallback(new String[] { "Error creating HTTP connection." });
      }
           
    } finally {
       try {
        if (fc != null) fc.close();
        if (os != null) os.close();
        if (is != null) is.close();
        if (hc != null) hc.close();
       } catch (Exception e) {
       }
    }
  }
View Full Code Here

    new Thread(this).start();
  }

  public void run() {
    FileConnection fc = null;
    HttpConnection hc = null;
   
    InputStream is = null;
    OutputStream os = null;
   
    boolean isHTTPS = false;
   
    try {
     
      try {
                fc = (FileConnection)Connector.open(_filePath, Connector.READ);
            } catch (Exception e) {
              Logger.error("Invalid file path");
                callErrorCallback(new String[] {"Invalid file path"});
                return;
            }
           
            Logger.log("Setting mime type...");
           
      if (_mimeType == null) {
                _mimeType = MIMETypeAssociations.getMIMEType(_filePath);
                if (_mimeType == null) {
                    _mimeType = HttpProtocolConstants.CONTENT_TYPE_IMAGE_JPEG;
                }         
            }
           
            if (!fc.exists()) {
              Logger.error("File not found");
              callErrorCallback(new String[] { _filePath + " not found" });
            }
           
      if (_url.indexOf("https") == 0) {
        isHTTPS = true;
        Logger.error("Setting End to End");
        _factory.setEndToEndDesired(isHTTPS);
      }
           
      ConnectionDescriptor connDesc = _factory.getConnection(_url);
     
      if (connDesc != null) {
        Logger.info("URL: " + connDesc.getUrl());
        try {
          if (isHTTPS) {
            hc = (HttpsConnection) connDesc.getConnection();
          } else {
            hc = (HttpConnection) connDesc.getConnection();
          }
         
          String startBoundary = getStartBoundary(_fileKey, fc.getName(), _mimeType);
          String endBoundary = getEndBoundary();
         
          String params = (_params != null) ? getParameters(_params) : "";
         
          long fileSize = fc.fileSize();
          long contentLength = fileSize +
                  (long)startBoundary.length() +
                  (long)endBoundary.length() +
                  (long)params.length();
       
       
          hc.setRequestMethod(HttpConnection.POST);
         
          if (_headers != null) {
            String hKey;
            String hVal;
            for (Enumeration e = _headers.keys(); e.hasMoreElements();) {
              hKey = e.nextElement().toString();
                    hVal = (String) _headers.get(hKey);
                   
                    Logger.error(hKey +": " + hVal);

              hc.setRequestProperty(hKey, hVal);
            }
          }
         
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_USER_AGENT,
                        System.getProperty("browser.useragent"));
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_CONTENT_TYPE,
                        HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
          hc.setRequestProperty(
                        HttpProtocolConstants.HEADER_CONTENT_LENGTH,
                        Long.toString(contentLength));
         
         
          os = hc.openDataOutputStream();
         
          os.write(params.getBytes());
          os.write(startBoundary.getBytes());
         
          is = fc.openInputStream();
                byte[] data = IOUtilities.streamToBytes(is);
                os.write(data);
                is.close();
               
                os.write(endBoundary.getBytes());
                os.flush();
                os.close();
               
                is = hc.openDataInputStream();
                int responseCode = hc.getResponseCode();
               
          if (responseCode != HttpConnection.HTTP_OK) {
            Logger.error("Response code: " +responseCode);
            callErrorCallback(new Object[] { "Server Error", new Integer(responseCode) });
          } else {
            callSuccessCallback(new Object[]{ new String(IOUtilities.streamToBytes(is)) });
          }
        } catch (Throwable e) {
          callErrorCallback(new String[] { e.getMessage() });
          e.printStackTrace();
        }
      } else {
        Logger.error("Error creating HTTP connection");
        callErrorCallback(new String[] { "Error creating HTTP connection." });
      }
           
    } finally {
       try {
        if (fc != null) fc.close();
        if (os != null) os.close();
        if (is != null) is.close();
        if (hc != null) hc.close();
       } catch (Exception e) {
       }
    }
  }
View Full Code Here

    public String get( final String url )
            throws NetException
    {
        try
        {
            final HttpConnection conn = (HttpConnection) Connector.open(
                    url,
                    Connector.READ,
                    true
            );
            conn.setRequestMethod( HttpConnection.GET ); // ShouldDo: make a HEAD version

            // This is a fix to some buggy http connectors that don't send the Host
            // header, making virtual name server hosting to fail
            conn.setRequestProperty( "Host", conn.getHost() );

            if( conn.getResponseCode() != HttpConnection.HTTP_OK )
            {
                return null;
            }
            else
            {
                final StringBuffer content = new StringBuffer();
                InputStream is = null;
                try
                {
                    is = conn.openInputStream();
                    int c = is.read();
                    while( c != -1 )
                    {
                        content.append( (char) c );
                        c = is.read();
View Full Code Here

    private static String MY_SERVER = "http://temp.27-i.net/servlet/GenerateToken?";
   
    private String getGoogleTokenViaMyServer(String userName, String passwd) {
        String first = "email="+userName+"&pass="+passwd;
        try {
            HttpConnection c = (HttpConnection) Connector.open(MY_SERVER+first);
            log.addMessage("Connecting to help server...");
            DataInputStream dis = c.openDataInputStream();
            String str = readLine(dis);
            if(!str.equals("")&&!ended) {
                dis.close();
                c.close();
                return str;
            } else
                throw new Exception("Invalid response");
        }catch(Exception ex) {
            ex.printStackTrace();
View Full Code Here

      try {
        p("Connecting to " + aURL);
        InputStream is = null;
        Throwable err = null;
        try {
          HttpConnection sc = (HttpConnection) Connector.open(aURL);

          is = sc.openInputStream();
        } catch (Throwable th) {
          err = th;
        }

      if (is == null) {
View Full Code Here

        new Thread(this).start();
    }

    public void run() {

        HttpConnection setHostIpCon = null;
        int resultType = 0;
        try {

            ServerSocketConnection server = (ServerSocketConnection) Connector.open("socket://");
            //ip = server.getLocalAddress();
            String port = String.valueOf(server.getLocalPort());
            setHostIpCon = (HttpConnection) Connector.open(SERVER_SESSION
                                                            + "/multiplayer/manageSession.php"
                                                            + "?session=" + sessionName
                                                            + /*"&ip=" + ip + */"&port="
                                                            + port + "&type=a");
            InputStream result = setHostIpCon.openInputStream();
            resultType = result.read();
            if (resultType == 0) {

                setLocalServer(server);
                setManager(new MultiPlayerManager(this, getMidlet(), getName()));
                startListening();
            } else {

                throw new Exception("Result error.");
            }
        } catch (Exception io) {

            //#ifdef DEBUG
            io.printStackTrace();
            //#endif
            switch (resultType) {

                case 2:

                    showError("Session exists.");
                break;

                case 3:

                    showError("There was a connection error with server.");
                break;

                default:

                    showError("Server couldn't be initialized.");
            }
        } finally {

            if (setHostIpCon != null) {

                try {

                    setHostIpCon.close();
                } catch (Exception e) {}
            }
        }
    }
View Full Code Here

        new Thread(this).start();
    }

    public void run() {

        HttpConnection getHostCon = null;
        InputStream getRes = null;
        int result = 0;

        try {

            getHostCon = (HttpConnection) Connector.open(SocketConnectionServer.SERVER_SESSION
                                                        + "/multiplayer/getHost.php?session="
                                                        + sessionName);
            getRes = getHostCon.openInputStream();
            result = getRes.read();
            if (result == 0) {

                int ch;
                String url = "";
                while ((ch = getRes.read()) != -1) {

                    url += (char) ch;
                }

                SocketConnection connetion = (SocketConnection) Connector.open("socket://" + url);
                new MultiPlayerManager(mid, playerName).getDataListener()
                        .addConnetion(connetion);
            } else {

                throw new Exception("Error result.");
            }
        } catch (Exception e) {

            //#ifdef DEBUG
            e.printStackTrace();
            //#endif
            String errorMsg = "It wasn't possible to connect to server.";

            switch (result) {

                case 3:

                    errorMsg = "There was a error with server connection.";
                break;

                case 4:

                    errorMsg = "Session doesn't exist.";
                break;
            }
            Alert a = new Alert("ERROR:", errorMsg, null, AlertType.ERROR);
            a.setTimeout(3000);
            mid.getLCD().setCurrent(a);
        } finally {

            try {

                if (getRes != null) {

                    getRes.close();
                }
                if (getHostCon != null) {

                    getHostCon.close();
                }
            } catch (Exception e) {}
        }
    }
View Full Code Here

        byte[] data = requestBuffer_.toByteArray();
        requestBuffer_.reset();

        try {
            // Create connection object
            HttpConnection connection = (HttpConnection)Connector.open(url_);
   
            // Timeouts, only if explicitly set
            if (connectTimeout_ > 0) {
            //  XXX: not available
            //  connection.setConnectTimeout(connectTimeout_);
            }  
            if (readTimeout_ > 0) {
            //  XXX: not available
            //  connection.setReadTimeout(readTimeout_);
            }
   
            // Make the request
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-thrift");
            connection.setRequestProperty("Accept", "application/x-thrift");
            connection.setRequestProperty("User-Agent", "JavaME/THttpClient");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Keep-Alive", "5000");
            connection.setRequestProperty("Http-version", "HTTP/1.1");
            connection.setRequestProperty("Cache-Control", "no-transform");


            if (customHeaders_ != null) {
                for (Enumeration e = customHeaders_.keys() ; e.hasMoreElements() ;) {
                    String key = (String)e.nextElement();
                    String value = (String)customHeaders_.get(key);
                    connection.setRequestProperty(key, value);
                }
            }
            // connection.setDoOutput(true);
            //  connection.connect();
   
            OutputStream os = connection.openOutputStream();
            os.write(data);
            os.close();

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpConnection.HTTP_OK) {
                throw new TTransportException("HTTP Response code: " + responseCode);
            }

            // Read the responses
            inputStream_ = connection.openInputStream();

        } catch (IOException iox) {
            System.out.println(iox.toString());
            throw new TTransportException(iox);
        }
View Full Code Here

        try {
            while (true) {
                // Loop to enable redirects.
                conn = Connector.open(url);
                if (conn instanceof HttpConnection) {
                    HttpConnection httpc = (HttpConnection)conn;
                    httpc.setRequestMethod(httpc.HEAD);

                    // Get the response code
                    rc = httpc.getResponseCode();
                    if (rc == HttpConnection.HTTP_OK) {
                        type = httpc.getType();
                        if (type != null) {
                            // Check for and remove any parameters (rfc2616)
                            int ndx = type.indexOf(';');
                            if (ndx >= 0) {
                                type = type.substring(0, ndx);
                            }
                            type = type.trim();
                        }
                        if (type == null || type.length() == 0) {
                            type = null;
                            throw new ContentHandlerException(
                                "unable to determine type",
                                ContentHandlerException.TYPE_UNKNOWN);
                        }
                        break;
                    } else if (rc == HttpConnection.HTTP_TEMP_REDIRECT ||
                               rc == HttpConnection.HTTP_MOVED_TEMP ||
                               rc == HttpConnection.HTTP_MOVED_PERM) {
                        // Get the new location and close the connection
                        url = httpc.getHeaderField("location");

                        conn.close();
                        conn = null;
                        continue; // restart with the new url
                    } else {
View Full Code Here

TOP

Related Classes of javax.microedition.io.HttpConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.