Example usage for org.apache.commons.httpclient HttpConnection HttpConnection

List of usage examples for org.apache.commons.httpclient HttpConnection HttpConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpConnection HttpConnection.

Prototype

public HttpConnection(String host, int port) 

Source Link

Document

Creates a new HTTP connection for the given host and port.

Usage

From source file:com.cellbots.communication.AppEngineCommChannel.java

private void resetConnection() {
    if (mHttpCmdUrl == null || mHttpCmdUrl.equals("")) {
        return;//from  w w  w  .ja  v a 2 s.  c  o m
    }
    try {
        mConnection = new HttpConnection(new URL(mHttpCmdUrl).getHost(), port);
        mConnection.open();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static Object getURLContent(String host, String url, int port) throws Exception {
    HttpMethod method;//from w w  w . j av a2 s .c  om
    try {
        method = new GetMethod(url);
        HttpConnection conn = new HttpConnection(host, port);
        String proxyHost;
        String proxyPort;
        if ((proxyHost = System.getProperty("http.proxyHost")) != null
                && (proxyPort = System.getProperty("http.proxyPort")) != null) {
            conn.setProxyHost(proxyHost);
            conn.setProxyPort(Integer.parseInt(proxyPort));
        }
        conn.open();
        method.execute(new HttpState(), conn);
        String inpTmp = method.getResponseBodyAsString();
        Reader in = new InputStreamReader(method.getResponseBodyAsStream());
        StringBuffer out = new StringBuffer();
        char[] buffer = new char[1024];
        for (int count = in.read(buffer); count >= 0; count = in.read(buffer)) {
            out.append(buffer, 0, count);
        }
        return out.toString();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
}

From source file:es.gva.cit.catalog.DiscoveryServiceClient.java

/**
 * It tries if the server is ready/* w  w w.  j  a  va 2  s . com*/
 * 
 * @return boolean true --> server is ready false --> server is not ready
 */
public boolean serverIsReady() throws ServerIsNotReadyException {
    Properties systemSettings = System.getProperties();

    Object isProxyEnabled = systemSettings.get("http.proxySet");
    if ((isProxyEnabled == null) || (isProxyEnabled.equals("false"))) {
        Socket sock;
        try {
            sock = new Socket(getUri().getHost(), getUri().getPort());
        } catch (UnknownHostException e) {
            throw new ServerIsNotReadyException(e);
        } catch (IOException e) {
            throw new ServerIsNotReadyException(e);
        }
        return (sock != null);
    } else {
        Object host = systemSettings.get("http.proxyHost");
        Object port = systemSettings.get("http.proxyPort");
        Object user = systemSettings.get("http.proxyUserName");
        Object password = systemSettings.get("http.proxyPassword");
        if ((host != null) && (port != null)) {
            int iPort = 80;
            try {
                iPort = Integer.parseInt((String) port);
            } catch (Exception e) {
                // Use 80
            }
            HttpConnection connection = new HttpConnection(getUri().getHost(), getUri().getPort());
            connection.setProxyHost((String) host);
            connection.setProxyPort(iPort);
            Authenticator.setDefault(new SimpleAuthenticator(user, password));

            try {
                connection.open();
                connection.close();
            } catch (IOException e) {
                throw new ServerIsNotReadyException(e);
            }
        }
    }
    return true;
}

From source file:com.cellbots.remoteEyes.RemoteEyesActivity.java

private void resetConnection() {
    Log.e("server", server);
    mConnection = new HttpConnection(server, port);
    try {/*from   ww  w  .ja v  a 2  s. c o  m*/
        mConnection.open();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.cellbots.local.EyesView.java

private void resetConnection() {
    if (isLocalUrl)
        return;/*from ww  w. j  a va2  s  .  c o  m*/
    try {
        String ip = new URL(putUrl).getHost();
        int port = new URL(putUrl).getPort();
        mConnection = new HttpConnection(ip, port == -1 ? 80 : port);
        mConnection.open();
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.cellbots.eyes.EyesActivity.java

private void resetConnection() {
    //Log.e("server", server);
    try {//from   w  ww.  j a va  2s .  c  o m
        String ip = new URL(putUrl).getHost();
        int port = new URL(putUrl).getPort();
        mConnection = new HttpConnection(ip, port == -1 ? 80 : port);
        mConnection.open();
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.cellbots.eyes.EyesActivity.java

private void resetAppEngineConnection() {
    mConnection = new HttpConnection("http://botczar.appspot.com/", port);
    try {/*w w  w.j  a va 2  s.  c  o  m*/
        mConnection.open();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.cocoon.generation.GenericProxyGenerator.java

/**
 * Get the request data, pass them on to the forwarder and return the result.
 *
 * TODO: much better header handling/*from  www.ja v a2 s .c om*/
 * TODO: handle non XML and bodyless responses (probably needs a smarter Serializer,
 *            since some XML has to go through the pipeline anyway.
 *
 * @see org.apache.cocoon.generation.Generator#generate()
 */
public void generate() throws IOException, SAXException, ProcessingException {
    RequestForwardingHttpMethod method = new RequestForwardingHttpMethod(request, destination);

    // Build the forwarded connection
    HttpConnection conn = new HttpConnection(destination.getHost(), destination.getPort());
    HttpState state = new HttpState();
    state.setCredentials(null, destination.getHost(),
            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
    method.setPath(path);

    // Execute the method
    method.execute(state, conn);

    // Send the output to the client: set the status code...
    response.setStatus(method.getStatusCode());

    // ... retrieve the headers from the origin server and pass them on
    Header[] methodHeaders = method.getResponseHeaders();
    for (int i = 0; i < methodHeaders.length; i++) {
        // there is more than one DAV header
        if (methodHeaders[i].getName().equals("DAV")) {
            response.addHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        } else if (methodHeaders[i].getName().equals("Content-Length")) {
            // drop the original Content-Length header. Don't ask me why but there
            // it's always one byte off
        } else {
            response.setHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        }
    }

    // no HTTP keepalives here...
    response.setHeader("Connection", "close");

    // Parse the XML, if any
    if (method.getResponseHeader("Content-Type").getValue().startsWith("text/xml")) {
        InputStream stream = method.getResponseBodyAsStream();
        parser.parse(new InputSource(stream), this.contentHandler, this.lexicalHandler);
    } else {
        // Just send a dummy XML
        this.contentHandler.startDocument();
        this.contentHandler.startElement("", "no-xml-content", "no-xml-content", XMLUtils.EMPTY_ATTRIBUTES);
        this.contentHandler.endElement("", "no-xml-content", "no-xml-content");
        this.contentHandler.endDocument();
    }

    // again, no keepalive here.
    conn.close();
}

From source file:org.apache.cocoon.transformation.DASLTransformer.java

protected void performSearchMethod(String query) throws SAXException {
    OptionsMethod optionsMethod = null;// ww w. ja v  a  2 s  . c om
    SearchMethod searchMethod = null;
    try {
        DOMStreamer propertyStreamer = new DOMStreamer(this.xmlConsumer);
        optionsMethod = new OptionsMethod(this.targetUrl);
        searchMethod = new SearchMethod(this.targetUrl, query);
        HttpURL url = new HttpURL(this.targetUrl);
        HttpState state = new HttpState();
        state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
        HttpConnection conn = new HttpConnection(url.getHost(), url.getPort());

        // eventcaching stuff
        SourceValidity extraValidity = makeWebdavEventValidity(url);
        if (extraValidity != null && m_validity != null)
            m_validity.add(extraValidity);
        // end eventcaching stuff

        WebdavResource resource = new WebdavResource(new HttpURL(this.targetUrl));
        if (!resource.exists()) {
            throw new SAXException("The WebDAV resource don't exist");
        }
        optionsMethod.execute(state, conn);
        if (!optionsMethod.isAllowed("SEARCH")) {
            throw new SAXException("The server doesn't support the SEARCH method");
        }
        int httpstatus = searchMethod.execute(state, conn);

        this.contentHandler.startElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG,
                XMLUtils.EMPTY_ATTRIBUTES);

        // something might have gone wrong, report it
        // 207 = multistatus webdav response
        if (httpstatus != 207) {

            this.contentHandler.startElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG,
                    XMLUtils.EMPTY_ATTRIBUTES);

            // dump whatever the server said
            propertyStreamer.stream(searchMethod.getResponseDocument());

            this.contentHandler.endElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG);

        } else {
            // show results

            Enumeration enumeration = searchMethod.getAllResponseURLs();

            while (enumeration.hasMoreElements()) {
                String path = (String) enumeration.nextElement();
                Enumeration properties = searchMethod.getResponseProperties(path);
                AttributesImpl attr = new AttributesImpl();
                attr.addAttribute(DASL_QUERY_NS, PATH_NODE_NAME, PREFIX + ":" + PATH_NODE_NAME, "CDATA", path);

                this.contentHandler.startElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME, attr);
                while (properties.hasMoreElements()) {
                    BaseProperty metadata = (BaseProperty) properties.nextElement();
                    Element propertyElement = metadata.getElement();
                    propertyStreamer.stream(propertyElement);
                }

                this.contentHandler.endElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME);
            }
        }

        this.contentHandler.endElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG);
    } catch (SAXException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (HttpException e1) {
        this.getLogger().error("Unable to contact Webdav server", e1);
        throw new SAXException("Unable to connect with server: ", e1);
    } catch (IOException e2) {
        throw new SAXException("Unable to connect with server: ", e2);
    } catch (NullPointerException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (Exception e) {
        throw new SAXException("Generic Error:", e);
    } finally {
        // cleanup
        if (searchMethod != null)
            searchMethod.releaseConnection();
        if (optionsMethod != null)
            optionsMethod.releaseConnection();
    }
}

From source file:org.apache.slide.webdav.event.NotificationTrigger.java

protected void notifySubscriber(String callback, String subscribers) {
    if (callback.startsWith(TCP_PROTOCOL)) {
        Domain.log("Notify subscribers with adress='" + callback + "' via TCP with id's " + subscribers,
                LOG_CHANNEL, Logger.INFO);
        NotifyMethod notifyMethod = new NotifyMethod(callback.toString());
        notifyMethod.addRequestHeader(H_SUBSCRIPTION_ID_RESPONSE, subscribers);
        try {// ww w.j  a v  a 2s  .  c om
            URL url = new URL(callback);
            notifyMethod.execute(new HttpState(),
                    new HttpConnection(url.getHost(), url.getPort() != -1 ? url.getPort() : 80));
        } catch (IOException e) {
            Domain.log("Notification of subscriber '" + callback.toString() + "' failed!");
        }
    } else if (callback.startsWith(UDP_PROTOCOL) && socket != null) {
        Domain.log("Notify subscribers with adress='" + callback + "' via UDP with id's " + subscribers + "\n",
                LOG_CHANNEL, Logger.INFO);
        try {
            URL url = new URL(TCP_PROTOCOL + callback.substring(UDP_PROTOCOL.length()));
            String notification = "NOTIFY " + callback + " HTTP/1.1\nSubscription-id: " + subscribers;
            byte[] buf = notification.getBytes();
            InetAddress address = InetAddress.getByName(url.getHost());
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address,
                    url.getPort() != -1 ? url.getPort() : 80);
            socket.send(packet);
        } catch (IOException e) {
            Domain.log("Notification of subscriber '" + callback.toString() + "' failed!", LOG_CHANNEL,
                    Logger.ERROR);
        }
    }
}