Examples of HttpConnection


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

Examples of javax.microedition.io.HttpConnection

    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

Examples of javax.microedition.io.HttpConnection

    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

Examples of mx4j.tools.remote.http.HTTPConnection

      super(url, environment);
   }

   protected MBeanServerConnection doGetMBeanServerConnection(Subject delegate) throws IOException
   {
      HTTPConnection catcher = ClientExceptionCatcher.newInstance(getHTTPConnection());
      return new HTTPConnectionMBeanServerConnection(catcher, delegate, getRemoteNotificationClientHandler());
   }
View Full Code Here

Examples of net.datacrow.core.http.HttpConnection

        }
       
        boolean checked = false;
        while (!checked) {
            try {
                HttpConnection conn =  HttpConnectionUtil.getConnection(address);
                InputStream is = conn.getInputStream();
                properties.load(is);

                String version = (String) properties.get(_VERSION);
                String downloadUrl = (String) properties.get(_DOWNLOAD_URL);
                String infoUrl = (String) properties.get(_INFO_URL);
View Full Code Here

Examples of net.datacrow.core.http.HttpConnection

      url = new URL( "http://" + server + "/~cddb/cddb.cgi" );
    } catch (MalformedURLException e) {
      throw new Exception(DcResources.getText("msgInvalidURLChangeSetting", url.toString()));
    }
       
        HttpConnection connection = HttpConnectionUtil.getConnection(url);

    try {
      PrintWriter out = new PrintWriter(connection.getOutputStream());
            String query = "cmd=" + command + "&hello=" + userLogin + "+" + userDomain + "+" +
                           clientName + "+" + clientVersion + "&proto="+ protocol;
            out.println(query);
            out.flush();
            out.close();
    } catch ( IOException e ) {
      throw new Exception(DcResources.getText("msgFreeDBServerUnreachable", e.getMessage()));
    }
   
    String output = connection.getString();

    //Preliminary freedb error check, error codes 4xx and 5xx indicate an error
    if (output.startsWith("4") || output.startsWith("5") || output.startsWith("202")) {
      throw new Exception(DcResources.getText("msgFreeDBServerReturnedError", output));
        }
View Full Code Here

Examples of net.datacrow.core.http.HttpConnection

       
        return document;
    }   
   
    public static String getHtmlCleaned(URL url, String charset, boolean cleanup) throws Exception {
        HttpConnection connection = HttpConnectionUtil.getConnection(url);
        String html = connection.getString(charset);
        connection.close();       
       
        if (html.contains("<html") || html.contains("<HTML")) {
            String title = StringUtils.getValueBetween("<title>", "</title>", html);
            html = StringUtils.getValueBetween("<body", "</body>", html);
            html = html.substring(html.indexOf(">") + 1);
View Full Code Here

Examples of org.apache.commons.httpclient.HttpConnection

     */
    public HttpConnection getConnectionWithTimeout(
        HostConfiguration hostConfiguration, long timeout)
    {

        HttpConnection httpConnection = getLocalHttpConnection();
        if (httpConnection == null)
        {
            httpConnection = new HttpConnection(hostConfiguration);
            setLocalHttpConnection(httpConnection);
            httpConnection.setHttpConnectionManager(this);
            this.params.populateParameters(httpConnection);
        }
        else
        {

            // make sure the host and proxy are correct for this connection
            // close it and set the values if they are not
            if (!hostConfiguration.hostEquals(httpConnection)
                || !hostConfiguration.proxyEquals(httpConnection))
            {

                if (httpConnection.isOpen())
                {
                    httpConnection.close();
                }

                httpConnection.setHost(hostConfiguration.getHost());
                httpConnection.setPort(hostConfiguration.getPort());
                httpConnection.setProtocol(hostConfiguration.getProtocol());
                httpConnection.setLocalAddress(hostConfiguration.getLocalAddress());

                httpConnection.setProxyHost(hostConfiguration.getProxyHost());
                httpConnection.setProxyPort(hostConfiguration.getProxyPort());
            }
            else
            {
                finishLastResponse(httpConnection);
            }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpConnection

            this.generateDebugOutput();
            return;
        }

        /* Call up the remote HTTP server */
        HttpConnection connection = new HttpConnection(this.method.getHostConfiguration());
        HttpState state = new HttpState();
        this.method.setFollowRedirects(true);
        int status = this.method.execute(state, connection);
        if (status == 404) {
            throw new ResourceNotFoundException("Unable to access \"" + this.method.getURI()
                    + "\" (HTTP 404 Error)");
        } else if ((status < 200) || (status > 299)) {
            throw new IOException("Unable to access HTTP resource at \""
                    + this.method.getURI().toString() + "\" (status=" + status + ")");
        }
        InputStream response = this.method.getResponseBodyAsStream();

        /* Let's try to set up our InputSource from the response output stream and to parse it */
        SAXParser parser = null;
        try {
            InputSource inputSource = new InputSource(response);
            parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
            parser.parse(inputSource, super.xmlConsumer);
        } catch (ComponentException ex) {
            throw new ProcessingException("Unable to get parser", ex);
        } finally {
            this.manager.release((Component) parser);
            this.method.releaseConnection();
            connection.close();
        }
    }
View Full Code Here

Examples of org.apache.commons.httpclient.HttpConnection

        this.xscriptObject = xscriptObject;
    }

    public XScriptObject invoke() throws ProcessingException
    {
        HttpConnection conn = null;

        try {
            if (action == null || action.equals("")) {
                action = "\"\"";
            }

            String host = url.getHost();
            int port = url.getPort();

            if (System.getProperty("http.proxyHost") != null) {
                String proxyHost = System.getProperty("http.proxyHost");
                int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
                conn = new HttpConnection(proxyHost, proxyPort, host, port);
            } else {
                conn = new HttpConnection(host, port);
            }

            PostMethod method = new PostMethod(url.getFile());
            String request;

            try {
                // Write the SOAP request body
                if (xscriptObject instanceof XScriptObjectInlineXML) {
                    // Skip overhead
                    request = ((XScriptObjectInlineXML) xscriptObject).getContent();
                } else {
                    StringBuffer bodyBuffer = new StringBuffer();
                    InputSource saxSource = xscriptObject.getInputSource();

                    Reader r = null;
                    // Byte stream or character stream?
                    if (saxSource.getByteStream() != null) {
                        r = new InputStreamReader(saxSource.getByteStream());
                    } else {
                        r = saxSource.getCharacterStream();
                    }

                    try {
                        char[] buffer = new char[1024];
                        int len;
                        while ((len = r.read(buffer)) > 0)
                            bodyBuffer.append(buffer, 0, len);
                    } finally {
                        if (r != null) {
                            r.close();
                        }
                    }

                    request = bodyBuffer.toString();
                }

            } catch (Exception ex) {
                throw new ProcessingException("Error assembling request", ex);
            }

            method.setRequestHeader(
                    new Header("Content-type", "text/xml; charset=\"utf-8\""));
            method.setRequestHeader(new Header("SOAPAction", action));
            method.setUseDisk(false);
            method.setRequestBody(request);

            method.execute(new HttpState(), conn);

            String ret = method.getResponseBodyAsString();
            int startOfXML = ret.indexOf("<?xml");
            if (startOfXML == -1) { // No xml?!
                throw new ProcessingException("Invalid response - no xml");
            }

            return new XScriptObjectInlineXML(
                    xscriptManager,
                    ret.substring(startOfXML));
        } catch (Exception ex) {
            throw new ProcessingException("Error invoking remote service: " + ex,
                    ex);
        } finally {
            try {
                if (conn != null)
                    conn.close();
            } catch (Exception ex) {
            }
        }
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.