Example usage for org.apache.commons.httpclient HttpClient getHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient getHostConfiguration

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:org.lnicholls.galleon.togo.ToGo.java

public ArrayList getRecordings(List tivos, ProgressListener progressIndicator) {

    ServerConfiguration serverConfiguration = Server.getServer().getServerConfiguration();

    ArrayList videos = new ArrayList();

    log.debug("getRecordings: " + tivos.size());

    log.debug("mServerConfiguration.getMediaAccessKey()=" + serverConfiguration.getMediaAccessKey().length());

    PersistentValue persistentValue = PersistentValueManager.loadPersistentValue("VideoServer.lastUpdate");

    if (persistentValue != null) {

        try//from   ww w.j  ava 2 s. c o  m

        {

            String value = persistentValue.getValue();

            Date date = new Date(value);

            Date now = new Date();

            if (now.getTime() - date.getTime() < 60 * 1000)

            {

                log.debug("backoff: tivo busy with goback download");

                return videos;

            }

        }

        catch (Throwable ex)

        {

            log.error("Could not retrieve video server last update", ex);

        }

    }

    if (serverConfiguration.getMediaAccessKey().length() > 0) {

        GetMethod get = null;

        Iterator tivosIterator = tivos.iterator();

        while (tivosIterator.hasNext()) {

            TiVo tivo = (TiVo) tivosIterator.next();

            HashMap shows = new HashMap();

            try {

                Protocol protocol = new Protocol("https", new TiVoSSLProtocolSocketFactory(), 443);

                HttpClient client = new HttpClient();

                client.getHostConfiguration().setHost(tivo.getAddress(), 443, protocol);

                Credentials credentials = new UsernamePasswordCredentials("tivo",
                        Tools.decrypt(serverConfiguration

                                .getMediaAccessKey()));

                client.getState().setCredentials("TiVo DVR", tivo.getAddress(), credentials);

                int total = -1;

                int counter = 0;

                do {

                    try {

                        String url = QUERY_CONTAINER + RECURSE + ITEM_COUNT + MAX + ANCHOR_OFFSET + counter;

                        log.debug(url);

                        get = new GetMethod(url);

                        client.executeMethod(get);

                        // log.debug(get.getResponseBodyAsString());

                        SAXReader saxReader = new SAXReader();

                        Document document = saxReader.read(get.getResponseBodyAsStream());

                        // Get the root element

                        Element root = document.getRootElement(); // <TiVoContainer>

                        Date lastChangedDate = new Date();

                        Element detailsElement = root.element("Details");

                        if (detailsElement != null) {

                            Element totalItemsElement = detailsElement.element("TotalItems");

                            if (totalItemsElement != null) {

                                try {

                                    total = Integer.parseInt(totalItemsElement.getText());

                                } catch (NumberFormatException ex) {

                                }

                            }

                            Element lastChangeDateElement = detailsElement.element("LastChangeDate");

                            if (lastChangeDateElement != null) {

                                try {

                                    lastChangedDate = Tools.hexDate(lastChangeDateElement.getText());

                                } catch (NumberFormatException ex) {

                                }

                            }

                        }

                        log.debug("lastChangedDate=" + lastChangedDate);

                        log.debug("tivo.getLastChangedDate()=" + tivo.getLastChangedDate());

                        log.debug("total=" + total);

                        log.debug("tivo.getNumShows()=" + tivo.getNumShows());

                        if (lastChangedDate.after(tivo.getLastChangedDate()) || total != tivo.getNumShows()) {

                            tivo.setLastChangedDate(lastChangedDate);

                            tivo.setNumShows(0);

                        } else {

                            // Nothing changed

                            synchronized (this) {

                                List recordings = VideoManager.listAll();

                                Iterator iterator = recordings.listIterator();

                                while (iterator.hasNext()) {

                                    Video video = (Video) iterator.next();

                                    if (video.getUrl() != null
                                            && video.getUrl().indexOf(tivo.getAddress()) != -1)

                                        videos.add(video);

                                }

                            }

                            break;

                        }

                        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {

                            Element child = (Element) iterator.next();

                            if (child.getName().equals("Item")) {

                                Video video = new Video();

                                video.setMimeType("mpeg");

                                video.setDateModified(new Date());

                                video.setParentalControls(Boolean.FALSE);

                                counter = counter + 1;

                                if (progressIndicator != null) {

                                    if (total > 0) {

                                        progressIndicator.progress(counter + " of " + total);

                                    } else

                                        progressIndicator.progress(counter + "");

                                }

                                Element details = child.element("Details");

                                if (details != null) {

                                    String value = Tools.getAttribute(details, "CopyProtected"); // <CopyProtected>Yes</CopyProtected>

                                    if (value != null) {

                                        if (value.equalsIgnoreCase("yes"))

                                            continue;

                                    }

                                    value = Tools.getAttribute(details, "Title");

                                    if (value != null)

                                        video.setTitle(value);

                                    value = Tools.getAttribute(details, "ParentalControls");

                                    if (value != null)

                                    {

                                        if (value.equalsIgnoreCase("yes"))

                                            video.setParentalControls(Boolean.TRUE);

                                    }

                                    value = Tools.getAttribute(details, "SourceSize");

                                    if (value != null)

                                        video.setSize(Long.parseLong(value));

                                    value = Tools.getAttribute(details, "Duration");

                                    if (value != null)

                                        try {

                                            video.setDuration(Integer.parseInt(value));

                                        } catch (NumberFormatException ex) {

                                            log.error("Could not set duration", ex);

                                        }

                                    value = Tools.getAttribute(details, "CaptureDate");

                                    if (value != null)

                                        video.setDateRecorded(Tools.hexDate(value));

                                    value = Tools.getAttribute(details, "EpisodeTitle");

                                    if (value != null)

                                        video.setEpisodeTitle(value);

                                    value = Tools.getAttribute(details, "Description");

                                    if (value != null)

                                        video.setDescription(value);

                                    value = Tools.getAttribute(details, "SourceChannel");

                                    if (value != null)

                                        video.setChannel(value);

                                    value = Tools.getAttribute(details, "SourceStation");

                                    if (value != null)

                                        video.setStation(value);

                                    value = Tools.getAttribute(details, "InProgress");

                                    if (value != null)

                                        video.setStatus(Video.STATUS_RECORDING);

                                    video.setSource(tivo.getAddress());
                                    video.setTivo(tivo.getName());

                                }

                                String detailsUrl = null;

                                Element links = child.element("Links");

                                if (links != null) {

                                    Element element = links.element("Content");

                                    if (element != null) {

                                        String value = Tools.getAttribute(element, "Url");

                                        if (value != null)

                                            video.setUrl(value);

                                    }

                                    element = links.element("CustomIcon");

                                    if (element != null) {

                                        String value = Tools.getAttribute(element, "Url");

                                        if (value != null) {

                                            video.setIcon(value.substring(value.lastIndexOf(":") + 1));

                                        }

                                    }

                                    element = links.element("TiVoVideoDetails");

                                    if (element != null) {

                                        String value = Tools.getAttribute(element, "Url");

                                        if (value != null) {

                                            URL path = new URL(value);

                                            detailsUrl = path.getPath() + "?" + path.getQuery();

                                            // getvideoDetails(client,

                                            // video,

                                            // path.getPath()+"?"+path.getQuery());

                                        }

                                    }

                                }

                                if (detailsUrl != null) {

                                    shows.put(video, detailsUrl);

                                    tivo.setNumShows(tivo.getNumShows() + 1);

                                }

                            }

                        }

                        Thread.sleep(100); // give the CPU some breathing

                    } finally {

                        if (get != null) {

                            get.releaseConnection();

                            get = null;

                        }

                    }

                } while (counter < total);

                // Get video details

                for (Iterator iterator = shows.keySet().iterator(); iterator.hasNext();) {

                    Video video = (Video) iterator.next();

                    String url = (String) shows.get(video);

                    getvideoDetails(client, video, url);

                    videos.add(video);

                    Thread.sleep(500); // give the CPU some breathing time

                }

            } catch (MalformedURLException ex) {

                Tools.logException(ToGo.class, ex);

            } catch (Exception ex) {

                Tools.logException(ToGo.class, ex);

                try

                {

                    Thread.sleep(10000); // give the CPU some breathing time

                }

                catch (Exception ex2) {
                }

            }

        }

    }

    return videos;

}

From source file:org.lnicholls.galleon.togo.ToGo.java

public boolean Download(Video video, CancelDownload cancelDownload) {

    ServerConfiguration serverConfiguration = Server.getServer().getServerConfiguration();
    GoBackConfiguration goBackConfiguration = Server.getServer().getGoBackConfiguration();

    ArrayList videos = new ArrayList();

    GetMethod get = null;//  www.j  av  a  2  s  .c om

    try {

        URL url = new URL(video.getUrl());

        Protocol protocol = new Protocol("https", new TiVoSSLProtocolSocketFactory(), 443);

        HttpClient client = new HttpClient();

        // TODO How to get TiVo address??

        client.getHostConfiguration().setHost(url.getHost(), 443, protocol);

        String password = Tools.decrypt(serverConfiguration.getMediaAccessKey());

        if (video.getParentalControls() != null && video.getParentalControls().booleanValue())

        {

            if (serverConfiguration.getPassword() == null)

                throw new NullPointerException("Parental Controls Password is null");

            password = password + Tools.decrypt(serverConfiguration.getPassword());

        }

        Credentials credentials = new UsernamePasswordCredentials("tivo", password);

        //client.getState().setCredentials("TiVo DVR", url.getHost(), credentials);

        client.getState().setCredentials(null, url.getHost(), credentials);

        get = new GetMethod(video.getUrl());

        client.executeMethod(get);

        if (get.getStatusCode() != 200)

        {

            log.debug("Status code: " + get.getStatusCode());

            return false;

        }

        InputStream input = get.getResponseBodyAsStream();

        String path = serverConfiguration.getRecordingsPath();

        File dir = new File(path);

        if (!dir.exists()) {

            dir.mkdirs();

        }

        String name = getFilename(video);
        File file = null;
        if (goBackConfiguration.isGroupByShow()) {
            if (video.getSeriesTitle() != null && video.getSeriesTitle().trim().length() > 0) {
                path = path + File.separator + clean(video.getSeriesTitle());
                File filePath = new File(path);
                if (!filePath.exists())
                    filePath.mkdirs();
                file = new File(path + File.separator + name);
            } else
                file = new File(path + File.separator + name);
        } else {
            file = new File(path + File.separator + name);
        }

        // TODO Handle retransfers

        /*
                
        if (file.exists() && video.getStatus()!=Video.STATUS_DOWNLOADING)
                
        {
                
           log.debug("duplicate file: "+file);
                
           try {
                
              List list = VideoManager.findByPath(file.getCanonicalPath());
                
              if (list!=null && list.size()>0)
                
              {
                
          video.setDownloadSize(file.length());
                
          video.setDownloadTime(0);
                
          video.setPath(file.getCanonicalPath());
                
          video.setStatus(Video.STATUS_DELETED);
                
          VideoManager.updateVideo(video);
                
          return true;
                
              }
                
           } catch (HibernateException ex) {
                
              log.error("Video update failed", ex);
                
           }
                
        }
                
        */

        log.info("Downloading: " + name);

        WritableByteChannel channel = new FileOutputStream(file, false).getChannel();

        long total = 0;

        double diff = 0.0;

        ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 4);

        byte[] bytes = new byte[1024 * 4];

        int amount = 0;

        int index = 0;

        long target = video.getSize();

        long start = System.currentTimeMillis();

        long last = start;

        while (amount == 0 && total < target) {

            while (amount >= 0 && !cancelDownload.cancel()) {

                if (index == amount) {

                    amount = input.read(bytes);

                    index = 0;

                    total = total + amount;

                }

                while (index < amount && buf.hasRemaining()) {

                    buf.put(bytes[index++]);

                }

                buf.flip();

                int numWritten = channel.write(buf);

                if (buf.hasRemaining()) {

                    buf.compact();

                } else {

                    buf.clear();

                }

                if ((System.currentTimeMillis() - last > 10000) && (total > 0)) {

                    try {

                        video = VideoManager.retrieveVideo(video.getId());

                        if (video.getStatus() == Video.STATUS_DOWNLOADING) {

                            diff = (System.currentTimeMillis() - start) / 1000.0;

                            if (diff > 0) {

                                video.setDownloadSize(total);

                                video.setDownloadTime((int) diff);

                                VideoManager.updateVideo(video);

                            }

                        }

                    } catch (HibernateException ex) {

                        log.error("Video update failed", ex);

                    }

                    last = System.currentTimeMillis();

                }

            }

            if (cancelDownload.cancel()) {

                channel.close();

                return false;

            }

        }

        diff = (System.currentTimeMillis() - start) / 1000.0;

        channel.close();

        if (diff != 0)

            log.info("Download rate=" + (total / 1024) / diff + " KBps");

        try {

            video.setPath(file.getCanonicalPath());

            VideoManager.updateVideo(video);

        } catch (HibernateException ex) {

            log.error("Video update failed", ex);

        }

    } catch (MalformedURLException ex) {

        Tools.logException(ToGo.class, ex, video.getUrl());

        return false;

    } catch (Exception ex) {

        Tools.logException(ToGo.class, ex, video.getUrl());

        return false;

    } finally {

        if (get != null)

            get.releaseConnection();

    }

    return true;

}

From source file:org.mapfish.print.config.Config.java

/**
 * Get or create the http client to be used to fetch all the map data.
 *///from  w  w w  .  j  a v a2  s  .c o m
public HttpClient getHttpClient(URI uri) {
    MultiThreadedHttpConnectionManager connectionManager = getConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);

    // httpclient is a bit pesky about loading everything in memory...
    // disabling the warnings.
    Logger.getLogger(HttpMethodBase.class).setLevel(Level.ERROR);

    // configure proxies for URI
    ProxySelector selector = ProxySelector.getDefault();

    List<Proxy> proxyList = selector.select(uri);
    Proxy proxy = proxyList.get(0);

    if (!proxy.equals(Proxy.NO_PROXY)) {
        InetSocketAddress socketAddress = (InetSocketAddress) proxy.address();
        String hostName = socketAddress.getHostName();
        int port = socketAddress.getPort();

        httpClient.getHostConfiguration().setProxy(hostName, port);
    }

    for (SecurityStrategy sec : security)
        if (sec.matches(uri)) {
            sec.configure(uri, httpClient);
            break;
        }
    return httpClient;
}

From source file:org.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, //from  ww w . ja  va 2 s  .c om
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.nuxeo.opensocial.helper.ProxyHelper.java

public static void fillProxy(HttpClient httpClient, String requestUri) {
    if (useProxy(requestUri)) {
        log.info(String.format("Configuring proxy for request: %s", requestUri));
        String proxyHost = getProxyHost();
        int proxyPort = getProxyPort();
        log.debug(String.format("Using proxy: %s:%d", proxyHost, proxyPort));
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (useAuthenticated()) {
            log.debug(String.format("Using credentials: %s:%s", getProxyLogin(), getProxyPassword()));
            httpClient.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort, null),
                    new UsernamePasswordCredentials(getProxyLogin(), getProxyPassword()));
        }/*ww  w  .jav a 2 s . c  o  m*/
    }
}

From source file:org.olat.core.util.httpclient.HttpClientFactory.java

/**
 * A HttpClient with basic authentication and host or port setting. Can only be used to retrieve relative URLs
 * /* ww w.  j a va2 s.  c om*/
 * @param host must not be NULL
 * @param port must not be NULL
 * @param protocol must not be NULL
 * @param user can be NULL
 * @param password can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String host, int port, String protocol, String user,
        String password) {
    HttpClient c = getHttpClientInstance(user, password);
    c.getHostConfiguration().setHost(host, port, protocol);
    return c;
}

From source file:org.olat.test.OlatJerseyTestCase.java

/**
 * @return bare bone HttpClient/*from   ww w  .ja  va2s  . c  o  m*/
 */
public HttpClient getHttpClient() {
    final HttpClient c = new HttpClient();
    c.getHostConfiguration().setHost(HOST, PORT, PROTOCOL);
    return c;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * /*  w ww  .java  2  s  . co m*/
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Uploads the zipfile to the OpenCms.<p>
 * /*from  w  w  w  . j a v a2  s . c  om*/
 * @param uploadFile the zipfile to upload
 */
private void uploadZipFile(File uploadFile) {

    m_action = m_actionOutputUpload;
    repaint();

    PostMethod post = new PostMethod(m_targetUrl);

    try {
        Part[] parts = new Part[5];
        parts[0] = new FilePart(uploadFile.getName(), uploadFile);
        parts[1] = new StringPart("action", "submitform");
        parts[2] = new StringPart("unzipfile", "true");
        parts[3] = new StringPart("uploadfolder", m_uploadFolder);
        parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath());

        HttpMethodParams methodParams = post.getParams();
        methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
        post.setRequestEntity(request);

        // add jsessionid query string
        String sessionId = getParameter("sessionId");
        String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
        post.setQueryString(query);
        post.addRequestHeader(C_JSESSIONID, sessionId);

        HttpClient client = new HttpClient();
        HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(5000);

        // add the session cookie
        client.getState();
        client.getHostConfiguration().getHost();

        HttpState initialState = new HttpState();
        URI uri = new URI(m_targetUrl, false);
        Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
        initialState.addCookie(sessionCookie);
        client.setState(initialState);

        // no execute the file upload
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            //return to the specified url and frame target
            getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
        } else {
            // create the error text
            String error = m_errorLine1 + "\n" + post.getStatusLine();
            //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
            getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        // finally delete the zipFile on the harddisc
        uploadFile.delete();
    }
}

From source file:org.openhab.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * //from   ww w. java  2  s .co  m
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}