Example usage for org.apache.commons.httpclient HttpMethod setRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethod setRequestHeader

Introduction

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

Prototype

public abstract void setRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {/*from  w w  w .ja v a 2  s .c  om*/
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:ch.cyberduck.core.dav.DAVResource.java

/**
 * Add all additionals headers that have been previously registered
 * with addRequestHeader to the method/*from w  w w . j av  a  2s.co m*/
 */
@Override
protected void generateAdditionalHeaders(HttpMethod method) {
    for (Object o : headers.keySet()) {
        String header = (String) o;
        method.setRequestHeader(header, (String) headers.get(header));
    }
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

private void configureMethod(HttpMethod method, String eid, String sessionId, String csrfNonce) {
    method.setFollowRedirects(false);//  www. j  ava  2s.  com
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
    method.setQueryString(new NameValuePair[] { new NameValuePair("eid", eid),
            new NameValuePair(REQUEST_PARAMETER_CSRF_NONCE, csrfNonce) });
}

From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

private void writeOutBoundHeaders(MultivaluedMap<String, Object> metadata, HttpMethod method) {
    for (Map.Entry<String, List<Object>> e : metadata.entrySet()) {
        List<Object> vs = e.getValue();
        if (vs.size() == 1) {
            method.setRequestHeader(e.getKey(), ClientRequest.getHeaderValue(vs.get(0)));
        } else {/* www .  ja  va 2 s  .  c o  m*/
            StringBuilder b = new StringBuilder();
            for (Object v : e.getValue()) {
                if (b.length() > 0) {
                    b.append(',');
                }
                b.append(ClientRequest.getHeaderValue(v));
            }
            method.setRequestHeader(e.getKey(), b.toString());
        }
    }
}

From source file:mitm.common.security.crl.HTTPCRLDownloadHandler.java

private Collection<? extends CRL> downloadCRLs(URI uri, TaskScheduler watchdog)
        throws IOException, HttpException, CRLException, FileNotFoundException {
    Collection<? extends CRL> crls = null;

    HttpClient httpClient = new HttpClient();

    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();

    params.setConnectionTimeout((int) downloadParameters.getConnectTimeout());
    params.setSoTimeout((int) downloadParameters.getReadTimeout());

    if (proxyInjector != null) {
        try {/*ww  w  . ja v  a2s.co  m*/
            proxyInjector.setProxy(httpClient);
        } catch (ProxyException e) {
            throw new IOException(e);
        }
    }

    HttpMethod getMethod = new GetMethod(uri.toString());

    getMethod.setFollowRedirects(true);
    getMethod.setRequestHeader("User-Agent", NetUtils.HTTP_USER_AGENT);

    /* 
     * Add watchdog that will interrupt the thread on timeout. we want the abort to fire first so add 50% 
     */
    Task threadWatchdogTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName());
    watchdog.addTask(threadWatchdogTask, (long) (downloadParameters.getTotalTimeout() * 1.5));

    /* 
     * Add watchdog that will abort the HTTPMethod on timeout. we want to close the input first so add 20% 
     */
    Task httpMethodAbortTimeoutTask = new HTTPMethodAbortTimeoutTask(getMethod, watchdog.getName());
    watchdog.addTask(httpMethodAbortTimeoutTask, (long) (downloadParameters.getTotalTimeout() * 1.2));

    try {
        logger.debug("Setting up a connection to: " + uri);

        int statusCode = 0;

        try {
            statusCode = httpClient.executeMethod(getMethod);
        } catch (IllegalArgumentException e) {
            /* 
             * HttpClient can throw IllegalArgumentException when the host is not set 
             */
            throw new CRLException(e);
        }

        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("Error getting CRL. Message: " + getMethod.getStatusLine());
        }

        InputStream urlStream = getMethod.getResponseBodyAsStream();

        if (urlStream == null) {
            throw new IOException("Response body is null.");
        }

        /* 
         * add a timeout watchdog on the input 
         */
        Task inputWatchdogTask = new InputStreamTimeoutTask(urlStream, watchdog.getName());

        watchdog.addTask(inputWatchdogTask, downloadParameters.getTotalTimeout());

        /*
         * we want to set a max on the number of bytes to download. We do not want
         * a rogue server to provide us with a 1 TB CRL.
         */
        InputStream limitInputStream = new SizeLimitedInputStream(urlStream, downloadParameters.getMaxBytes());

        ReadableOutputStreamBuffer output = new ReadableOutputStreamBuffer(memThreshold);

        try {
            IOUtils.copy(limitInputStream, output);

            if (threadWatchdogTask.hasRun() || httpMethodAbortTimeoutTask.hasRun()
                    || inputWatchdogTask.hasRun()) {
                /* a timeout has occurred */
                throw new IOException(TIMEOUT_ERROR + uri);
            }

            try {
                InputStream input = output.getInputStream();

                try {
                    crls = CRLUtils.readCRLs(input);
                } finally {
                    IOUtils.closeQuietly(input);
                }

                if (crls == null || crls.size() == 0) {
                    logger.debug("No CRLs found in the downloaded stream.");
                }
            } catch (CertificateException e) {
                throw new CRLException(e);
            } catch (NoSuchProviderException e) {
                throw new CRLException(e);
            } catch (SecurityFactoryFactoryException e) {
                throw new CRLException(e);
            }
        } finally {
            /* 
             * we need to close ReadableOutputStreamBuffer to prevent temp file leak 
             */
            IOUtils.closeQuietly(output);
        }
    } finally {
        getMethod.releaseConnection();
    }

    return crls;
}

From source file:at.ait.dme.yuma.suite.apps.map.server.geo.GeocoderServiceImpl.java

private ArrayList<PlainLiteral> getAlternativePlacenames(String placename) {
    ArrayList<PlainLiteral> altLabels = new ArrayList<PlainLiteral>();

    try {/*from  w ww .  ja  va2 s .c  om*/
        HttpClient client = new HttpClient();
        HttpMethod get = new GetMethod("http://dbpedia.org/resource/" + URLEncoder.encode(placename, "UTF-8"));
        get.setRequestHeader("Content-Type", "application/rdf+xml; charset=UTF-8");
        get.setRequestHeader("Accept", "application/rdf+xml");

        int statusCode = client.executeMethod(get);
        if (statusCode == HttpStatus.SC_OK) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder
                    .parse(new InputSource(new InputStreamReader(get.getResponseBodyAsStream(), "UTF-8")));

            NodeList labels = doc.getElementsByTagName("rdfs:label");
            for (int i = 0; i < labels.getLength(); i++) {
                altLabels.add(new PlainLiteral(labels.item(i).getTextContent()));
            }
        }
    } catch (Exception e) {
        // Just ignore for now - doesn't have adverse effect on functionality
    }

    return altLabels;
}

From source file:com.ideabase.repository.webservice.client.impl.HttpWebServiceControllerImpl.java

/**
 * {@inheritDoc}//from ww  w.  ja va2s.  c  o  m
 */
public WebServiceResponse sendServiceRequest(final WebServiceRequest pRequest) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending request - " + pRequest);
    }
    // build query string
    final NameValuePair[] parameters = buildParameters(pRequest);

    // Send request to server
    final HttpMethod httpMethod = prepareMethod(pRequest.getRequestMethod(), pRequest.getServiceUri(),
            parameters);

    // set cookie policy
    httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

    // set cookies
    if (mCookies != null) {
        httpMethod.setRequestHeader(HEADER_COOKIE, mCookies);
    }
    if (pRequest.getCookies() != null) {
        httpMethod.setRequestHeader(HEADER_COOKIE, pRequest.getCookies());
        mCookies = pRequest.getCookies();
    }

    // execute method
    final HttpClient httpClient = new HttpClient();
    final WebServiceResponse response;
    try {
        final int status = httpClient.executeMethod(httpMethod);

        // build web sercie response
        response = new WebServiceResponse();
        response.setResponseStatus(status);
        response.setResponseContent(new String(httpMethod.getResponseBody()));
        response.setContentType(httpMethod.getResponseHeader(HEADER_CONTENT_TYPE).getValue());
        response.setServiceUri(httpMethod.getURI().toString());

        // set cookies
        final Header cookieHeader = httpMethod.getResponseHeader(HEADER_SET_COOKIE);
        if (cookieHeader != null) {
            mCookies = cookieHeader.getValue();
        }

        // set cookies to the returning response object.
        response.setCookies(mCookies);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Cookies - " + mCookies);
            LOG.debug("Response - " + response);
        }
    } catch (Exception e) {
        throw ServiceException.aNew(pRequest, "Failed to send web service request.", e);
    } finally {
        httpMethod.releaseConnection();
    }

    return response;
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Prepares a HttpMethod object./*from w ww  .  j  a v  a  2  s .  co  m*/
 *
 * @param method The object which gets prepared to access the file object.
 * @throws FileSystemException if an error occurs.
 * @throws URIException if path cannot be represented.
 * @since 2.0 (was package)
 */
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", this.getUserAgent());
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.SoapHeadersRequestFilter.java

public void filterWsdlRequest(SubmitContext context, WsdlRequest wsdlRequest) {
    HttpMethod postMethod = (HttpMethod) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    WsdlInterface wsdlInterface = (WsdlInterface) wsdlRequest.getOperation().getInterface();

    // init content-type and encoding
    String encoding = System.getProperty("soapui.request.encoding", wsdlRequest.getEncoding());

    SoapVersion soapVersion = wsdlInterface.getSoapVersion();
    String soapAction = wsdlRequest.isSkipSoapAction() ? null : wsdlRequest.getAction();

    postMethod.setRequestHeader("Content-Type", soapVersion.getContentTypeHttpHeader(encoding, soapAction));

    if (!wsdlRequest.isSkipSoapAction()) {
        String soapActionHeader = soapVersion.getSoapActionHeader(soapAction);
        if (soapActionHeader != null)
            postMethod.setRequestHeader("SOAPAction", soapActionHeader);
    }/*from w ww .  java2  s .  c  om*/
}

From source file:com.xpn.xwiki.plugin.feed.XWikiFeedFetcher.java

/**
 * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL)
 *//*from  w w w .j  a  v a2  s.c  om*/
public SyndFeed retrieveFeed(URL feedUrl, int timeout)
        throws IllegalArgumentException, IOException, FeedException, FetcherException {
    if (feedUrl == null) {
        throw new IllegalArgumentException("null is not a valid URL");
    }
    HttpClient client = new HttpClient();
    if (timeout != 0) {
        client.getParams().setSoTimeout(timeout);
        client.getParams().setParameter("http.connection.timeout", new Integer(timeout));
    }

    System.setProperty("http.useragent", getUserAgent());
    client.getParams().setParameter("httpclient.useragent", getUserAgent());

    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if ((proxyHost != null) && (!proxyHost.equals(""))) {
        int port = 3128;
        if ((proxyPort != null) && (!proxyPort.equals(""))) {
            port = Integer.parseInt(proxyPort);
        }
        client.getHostConfiguration().setProxy(proxyHost, port);
    }

    String proxyUser = System.getProperty("http.proxyUser");
    if ((proxyUser != null) && (!proxyUser.equals(""))) {
        String proxyPassword = System.getProperty("http.proxyPassword");
        Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
    }

    String urlStr = feedUrl.toString();
    FeedFetcherCache cache = getFeedInfoCache();
    if (cache != null) {
        // retrieve feed
        HttpMethod method = new GetMethod(urlStr);
        method.addRequestHeader("Accept-Encoding", "gzip");
        try {
            if (isUsingDeltaEncoding()) {
                method.setRequestHeader("A-IM", "feed");
            }

            // get the feed info from the cache
            // Note that syndFeedInfo will be null if it is not in the cache
            SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl);
            if (syndFeedInfo != null) {
                method.setRequestHeader("If-None-Match", syndFeedInfo.getETag());

                if (syndFeedInfo.getLastModified() instanceof String) {
                    method.setRequestHeader("If-Modified-Since", (String) syndFeedInfo.getLastModified());
                }
            }

            method.setFollowRedirects(true);

            int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode);

            syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode);

            cache.setFeedInfo(new URL(urlStr), syndFeedInfo);

            // the feed may have been modified to pick up cached values
            // (eg - for delta encoding)
            feed = syndFeedInfo.getSyndFeed();

            return feed;
        } finally {
            method.releaseConnection();
        }
    } else {
        // cache is not in use
        HttpMethod method = new GetMethod(urlStr);
        try {
            method.setFollowRedirects(true);

            int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            return getFeed(null, urlStr, method, statusCode);
        } finally {
            method.releaseConnection();
        }
    }
}