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

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

Introduction

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

Prototype

public abstract Header getResponseHeader(String paramString);

Source Link

Usage

From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java

public boolean startup() {

    if (GraphicsEnvironment.isHeadless()) {
        return true; // if we are running headlessly just return
    }//from   www  .j  a v  a 2 s.c om

    long noticeTime = -1;
    long lastCheckedTime = -1;

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    PluginManager.setProxy(client);
    String message = null;

    try {
        URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX);
        HttpMethod method = new GetMethod(noticeURI.toString());
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting " + noticeURI);
            return true;
        }
        String noticeTimeString = null;
        Header h = method.getResponseHeader("Last-Modified");
        message = method.getResponseBodyAsString();
        if (h != null) {
            noticeTimeString = h.getValue();
            noticeTime = format.parse(noticeTimeString).getTime();
            logger.info("NoticeTime is " + noticeTime);
        }

    } catch (URISyntaxException e) {
        logger.error("URI problem", e);
        return true;
    } catch (IOException e) {
        logger.info("Could not read notice", e);
    } catch (ParseException e) {
        logger.error("Could not parse last-modified time", e);
    }

    if (lastNoticeCheckFile.exists()) {
        lastCheckedTime = lastNoticeCheckFile.lastModified();
    }

    if ((message != null) && (noticeTime != -1)) {
        if (noticeTime > lastCheckedTime) {
            // Show the notice dialog
            JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE,
                    WorkbenchIcons.tavernaCogs64x64Icon);
            try {
                FileUtils.touch(lastNoticeCheckFile);
            } catch (IOException e) {
                logger.error("Unable to touch file", e);
            }
        }
    }
    return true;
}

From source file:org.apache.wookie.proxy.ProxyClient.java

private String executeMethod(HttpMethod method, Configuration properties)
        throws Exception, AuthenticationException {
    // Execute the method.
    try {/*from w w  w . j a v a2  s .  c o  m*/
        HttpClient client = new HttpClient();

        // set the clients proxy values if needed
        ConnectionsPrefsManager.setProxySettings(client, properties);

        if (fUseProxyAuthentication) {
            if (fBase64Auth != null) {
                method.setRequestHeader("Authorization", fBase64Auth);
            } else {
                List<String> authPrefs = new ArrayList<String>(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);
                client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
                // send the basic authentication response even before the server gives an unauthorized response
                client.getParams().setAuthenticationPreemptive(true);
                // Pass our credentials to HttpClient
                client.getState().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(fProxyUsername, fProxyPassword));
            }
        }

        // Add user language to http request in order to notify server of user's language
        Locale locale = Locale.getDefault();

        method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$
        method.removeRequestHeader("Content-Type");
        //method.setRequestHeader("Content-Type","application/json");
        //method.setRequestHeader("Referer", "");
        //method.removeRequestHeader("Referer");
        method.setRequestHeader("Accept", "*/*");

        int statusCode = client.executeMethod(method);

        //System.out.println("response="+method.getResponseBodyAsString());
        //System.out.println("method="+method.toString());
        //System.out.println("response="+method.getResponseBodyAsStream());

        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            Header hType = method.getResponseHeader("Content-Type");
            if (hType != null) {
                fContentType = hType.getValue();
            }
            // for now we are only expecting Strings
            //return method.getResponseBodyAsString();
            return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
                || statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' '
                    + method.getURI() + ' ' + method.getStatusText());
        } else {
            throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$
                    + method.getStatusText());
        }
    } catch (IOException e) {
        throw e;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getValidSiteAndValidXMLContentType() throws Exception {
    String url = PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + VALID_SITE_XML_URL;
    HttpClient client = new HttpClient();
    HttpMethod req = new GetMethod(url);
    client.executeMethod(req);//from w w  w  .  java  2  s  .  c  o  m
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
    assertTrue(req.getResponseHeader("Content-Type").toString().contains("text/xml"));
}

From source file:org.apache.wookie.tests.functional.ProxyTest.java

@Test
public void getValidSiteAndValidHTMLContentType() throws Exception {
    String url = PROXY_URL + "?instanceid_key=" + instance_id_key + "&url=" + VALID_SITE_URL;
    HttpClient client = new HttpClient();
    HttpMethod req = new GetMethod(url);
    client.executeMethod(req);//from   www  .j a v a 2s.co m
    int code = req.getStatusCode();
    req.releaseConnection();
    assertEquals(200, code);
    assertTrue(req.getResponseHeader("Content-Type").toString().contains("text/html"));
}

From source file:org.araqne.pkg.HttpWagon.java

private static String getRealm(HttpMethod method) throws IOException {
    Header responseHeader = method.getResponseHeader("WWW-Authenticate");
    if (responseHeader != null) {
        String value = responseHeader.getValue();
        String realmStr = "realm=\"";
        int realmPos = value.indexOf(realmStr);
        if (realmPos == -1)
            throw new IOException("digest auth failed: Unsupported auth scheme");
        int realmEndPos = value.indexOf("\"", realmPos + realmStr.length() + 1);
        return value.substring(realmPos + realmStr.length(), realmEndPos);
    }//from w w w.  j a v  a 2  s .c  om
    return null;
}

From source file:org.archive.modules.deciderules.NotExceedsDocumentLengthTresholdDecideRule.java

protected boolean evaluate(CrawlURI curi) {
    int contentlength = HEADER_PREDICTS_MISSING;

    // filter used as midfetch filter
    if (getUseHeaderLength()) {

        if (curi.getHttpMethod() == null) {
            // Missing header info, let pass
            if (logger.isLoggable(Level.INFO)) {
                logger.info("Error: Missing HttpMethod object in " + "CrawlURI. " + curi.toString());
            }/*from  w w w.j  a  v a  2 s  . co m*/
            return false;
        }

        // Initially assume header info is missing
        HttpMethod method = curi.getHttpMethod();

        // get content-length
        String newContentlength = null;
        if (method.getResponseHeader("content-length") != null) {
            newContentlength = method.getResponseHeader("content-length").getValue();
        }

        if (newContentlength != null && newContentlength.length() > 0) {
            try {
                contentlength = Integer.parseInt(newContentlength);
            } catch (NumberFormatException nfe) {
                // Ignore.
            }
        }

        // If no document length was reported or format was wrong,
        // let pass
        if (contentlength == HEADER_PREDICTS_MISSING) {
            return false;
        }
    } else {
        contentlength = (int) curi.getContentSize();
    }

    return test(contentlength);
}

From source file:org.archive.modules.recrawl.FetchHistoryProcessor.java

/**
 * Save a header from the given HTTP operation into the AList.
 * /* w  w  w  .  j a va 2s .c  om*/
 * @param name header name to save into history AList
 * @param method http operation containing headers
 * @param latestFetch AList to get header
 */
protected void saveHeader(String name, HttpMethod method, HashMap<String, Object> latestFetch) {
    Header header = method.getResponseHeader(name);
    if (header != null) {
        latestFetch.put(name, header.getValue());
    }
}

From source file:org.archive.modules.writer.WARCWriterProcessor.java

/**
 * Save a header from the given HTTP operation into the 
 * provider headers under a new name//from w w w. j  av  a2 s .  c o  m
 * 
 * @param origName header name to get if present
 * @param method http operation containing headers
 */
protected void saveHeader(String origName, HttpMethod method, ANVLRecord headers, String newName) {
    Header header = method.getResponseHeader(origName);
    if (header != null) {
        headers.addLabelValue(newName, header.getValue());
    }
}

From source file:org.artifactory.cli.rest.RestClient.java

/**
 * Executes a configured HTTP//from w  w  w .ja v a 2s  .co  m
 *
 * @param uri                Target URL
 * @param method             Method to execute
 * @param expectedStatus     Expected return status
 * @param expectedResultType Expected response media type
 * @param timeout            Request timeout
 * @param credentials        For authentication
 * @throws Exception
 */
private static byte[] executeMethod(String uri, HttpMethod method, int expectedStatus,
        String expectedResultType, int timeout, Credentials credentials, boolean printStream)
        throws IOException {
    try {
        getHttpClient(uri, timeout, credentials).executeMethod(method);
        checkStatus(uri, expectedStatus, method);
        Header contentTypeHeader = method.getResponseHeader("content-type");
        if (contentTypeHeader != null) {
            //Check result content type
            String contentType = contentTypeHeader.getValue();
            checkContentType(uri, expectedResultType, contentType);
        }
        return analyzeResponse(method, printStream);
    } catch (SSLException ssle) {
        throw new RemoteCommandException("\nThe host you are trying to reach does not support SSL.");
    } catch (ConnectTimeoutException cte) {
        throw new RemoteCommandException("\n" + cte.getMessage());
    } catch (UnknownHostException uhe) {
        throw new RemoteCommandException("\nThe host of the specified URL: " + uri + " could not be found.\n"
                + "Please make sure you have specified the correct path. The default should be:\n"
                + "http://myhost:8081/artifactory/api/system");
    } catch (ConnectException ce) {
        throw new RemoteCommandException("\nCannot not connect to: " + uri + ". "
                + "Please make sure to specify a valid host (--host <host>:<port>) or URL (--url http://...).");
    } catch (NoRouteToHostException nrthe) {
        throw new RemoteCommandException("\nCannot reach: " + uri + ".\n"
                + "Please make sure that the address is valid and that the port is open (firewall, router, etc').");
    } finally {
        method.releaseConnection();
    }
}

From source file:org.bibsonomy.util.WebUtils.java

/**
 * Reads from a URL and writes the content into a string.
 * //from w  w w. ja  va 2 s  . c om
 * @param url
 * @param cookie
 * @param postData 
 * @param visitBefore
 * 
 * @return String which holds the page content.
 * 
 * @throws IOException
 */
public static String getContentAsString(final String url, final String cookie, final String postData,
        final String visitBefore) throws IOException {
    if (present(visitBefore)) {
        /*
         * visit URL to get cookies if needed
         */
        client.executeMethod(new GetMethod(visitBefore));
    }

    final HttpMethod method;
    if (present(postData)) {
        /*
         * do a POST request
         */
        final List<NameValuePair> data = new ArrayList<NameValuePair>();

        for (final String s : postData.split(AMP_SIGN)) {
            final String[] p = s.split(EQUAL_SIGN);

            if (p.length != 2) {
                continue;
            }

            data.add(new NameValuePair(p[0], p[1]));
        }

        method = new PostMethod(url);
        ((PostMethod) method).setRequestBody(data.toArray(new NameValuePair[data.size()]));
    } else {
        /*
         * do a GET request
         */
        method = new GetMethod(url);
        method.setFollowRedirects(true);
    }

    /*
     * set cookie
     */
    if (present(cookie)) {
        method.setRequestHeader(COOKIE_HEADER_NAME, cookie);
    }

    /*
     * do request
     */
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException(url + " returns: " + status);
    }

    /*
     * FIXME: check content type header to ensure that we only read textual 
     * content (and not a PDF, radio stream or DVD image ...)
     */

    /*
     * collect response
     */
    final String charset = extractCharset(method.getResponseHeader(CONTENT_TYPE_HEADER_NAME).getValue());
    final StringBuilder content = inputStreamToStringBuilder(method.getResponseBodyAsStream(), charset);
    method.releaseConnection();

    final String string = content.toString();
    if (string.length() > 0) {
        return string;
    }

    return null;

}