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:net.sf.ehcache.constructs.web.AbstractWebTest.java

/**
 * Orion returns a length of 0. Tomcat does not set content length at all.
 *
 * @param httpMethod/*from   w  w  w . j av  a2s  . c  o m*/
 */
protected void checkNullOrZeroContentLength(HttpMethod httpMethod) {
    boolean nullContentLengthHeader = httpMethod.getResponseHeader("Content-Length") == null;
    if (!nullContentLengthHeader) {
        assertEquals("0", httpMethod.getResponseHeader("Content-Length").getValue());
    }
}

From source file:com.dtolabs.client.utils.BaseFormAuthenticator.java

/**
 * Return true if the result from the get method indicates re-authentication is needed
 *
 * @param resultCode result code//from w w w . ja  va  2s  .com
 * @param method     request
 *
 * @return true if re-authentication is needed
 */
public boolean needsReAuthentication(final int resultCode, final HttpMethod method) {
    if (resultCode >= 300 && resultCode < 400 && method.getResponseHeader("Location") != null) {
        final String loc = method.getResponseHeader("Location").getValue();
        final int logNdx = loc.indexOf(LOGIN_PAGE);
        final int qNdx = loc.indexOf("?");
        if (logNdx >= 0 && (qNdx < 0 || logNdx < qNdx)) {
            //if "user/login" is in the location and is not after query part of URL
            //reset session cookie then return true
            ClientState.resetHttpState();
            return true;
        }
    } else if (HttpStatus.SC_OK == resultCode) {
        final String loc = method.getPath();
        final int logNdx = loc.indexOf(LOGIN_PAGE);
        final int qNdx = loc.indexOf("?");
        if (logNdx >= 0 && (qNdx < 0 || logNdx < qNdx)) {
            //if "user/login" is in the location and is not after query part of URL
            //reset session cookie then return true
            ClientState.resetHttpState();
            return true;
        }
    }
    return false;
}

From source file:is.hi.bok.deduplicator.DeDupFetchHTTP.java

/**
 * Checks if the 'etag' in the HTTP header and compares it against the etag in the supplied Lucene document. If both
 * dates are found and match then the datestamp indicate non-change. Otherwise a change must be assumed.
 *
 * @param method HTTPMethod that allows access to the relevant HTTP header
 * @param doc The Lucene document to compare against
 * @return True if a the header and document data indicates a non-change. False otherwise.
 *//*w  w  w. j  ava  2s  . c om*/
protected boolean etagIndicatesNonChange(HttpMethod method, Document doc) {
    String headerEtag = null;
    if (method.getResponseHeader("last-etag") != null) {
        headerEtag = method.getResponseHeader("last-etag").getValue();
    }
    String indexEtag = doc.get(DigestIndexer.FIELD_ETAG);

    if (headerEtag != null && indexEtag != null) {
        // If both etags exist and are identical then we assume no
        // change has occured.
        return headerEtag.equals(indexEtag);
    }
    return false;
}

From source file:is.hi.bok.deduplicator.DeDupFetchHTTP.java

/**
 * Checks if the 'last-modified' in the HTTP header and compares it against the timestamp in the supplied Lucene
 * document. If both dates are found and the header's date is older then the datestamp indicates non-change.
 * Otherwise a change must be assumed.//from  ww w .  j ava  2s  . c om
 *
 * @param method HTTPMethod that allows access to the relevant HTTP header
 * @param doc The Lucene document to compare against
 * @return True if a the header and document data indicates a non-change. False otherwise.
 */
protected boolean datestampIndicatesNonChange(HttpMethod method, Document doc) {
    String headerDate = null;
    if (method.getResponseHeader("last-modified") != null) {
        headerDate = method.getResponseHeader("last-modified").getValue();
    }
    String indexDate = doc.get(DigestIndexer.FIELD_TIMESTAMP);

    if (headerDate != null && indexDate != null) {
        try {
            // If both dates exist and last-modified is before the index
            // date then we assume no change has occured.
            return (sdfLastModified.parse(headerDate)).before(sdfIndexDate.parse(indexDate));
        } catch (Exception e) {
            // Any exceptions parsing the date should be interpreted as
            // missing date information.
            // ParseException and NumberFormatException are the most
            // likely exceptions to occur.
            return false;
        }
    }
    return false;
}

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.j  a  v a  2s  .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:eu.delving.services.controller.SolrProxyController.java

@RequestMapping("/api/solr/select")
public void searchController(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final String solrQueryString = request.getQueryString();
    HttpMethod method = new GetMethod(
            String.format("%s/select?%s", ThemeFilter.getTheme().getSolrSelectUrl(), solrQueryString));
    httpClient.executeMethod(method);//  w  w w.  jav a  2s.  c o  m
    Boolean getAsStream = false;
    for (Header header : method.getResponseHeaders()) {
        if (header.getName().equalsIgnoreCase("content-type")) {
            final String contentType = method.getResponseHeader("Content-Type").getValue();
            response.setContentType(contentType);
            response.setHeader(header.getName(), header.getValue());
            if (contentType.equalsIgnoreCase("application/octet-stream")) {
                getAsStream = true;
            }
        } else if (header.getName().equalsIgnoreCase("server")) {
            //ignore
        } else {
            response.setHeader(header.getName(), header.getValue());
        }
    }
    response.setCharacterEncoding("UTF-8");
    if (getAsStream) {
        OutputStream out = response.getOutputStream();
        try {
            IOUtils.copy(method.getResponseBodyAsStream(), out);
        } finally {
            out.close();
        }
    } else {
        response.getWriter().write(method.getResponseBodyAsString()); //todo add response from SolrProxy here
        response.getWriter().close();
    }
}

From source file:com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.java

/**
* @param client/*from   w ww.  j ava  2s  . c  o  m*/
* @param urlStr
* @param method
* @return
* @throws IOException
* @throws HttpException
* @throws FetcherException
* @throws FeedException
*/
private SyndFeed retrieveFeed(String urlStr, HttpMethod method)
        throws IOException, HttpException, FetcherException, FeedException {

    InputStream stream = null;
    if ((method.getResponseHeader("Content-Encoding") != null)
            && ("gzip".equalsIgnoreCase(method.getResponseHeader("Content-Encoding").getValue()))) {
        stream = new GZIPInputStream(method.getResponseBodyAsStream());
    } else {
        stream = method.getResponseBodyAsStream();
    }
    try {
        XmlReader reader = null;
        if (method.getResponseHeader("Content-Type") != null) {
            reader = new XmlReader(stream, method.getResponseHeader("Content-Type").getValue(), true);
        } else {
            reader = new XmlReader(stream, true);
        }
        SyndFeedInput syndFeedInput = new SyndFeedInput();
        syndFeedInput.setPreserveWireFeed(isPreserveWireFeed());

        return syndFeedInput.build(reader);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java

private int followRedirections(HttpMethod httpMethod) throws IOException {
    int redirectionsCount = 0;
    int status = httpMethod.getStatusCode();
    while (redirectionsCount < 3 && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header location = httpMethod.getResponseHeader("Location");
        if (location == null) {
            location = httpMethod.getResponseHeader("location");
        }/*from  ww w.  jav a 2  s .co  m*/
        if (location == null) {
            Log.e(TAG, "No valid location header found when redirecting.");
            return 500;
        }

        try {
            httpMethod.setURI(new URI(location.getValue()));
        } catch (URIException e) {
            Log.e(TAG, "Invalid URI in 302 FOUND response");
            return 500;
        }

        status = executeMethod(httpMethod);
        redirectionsCount++;
    }

    if (redirectionsCount >= 3 && status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT) {
        Log.e(TAG,
                "Too many redirection done. Aborting, please ensure your server is " + "correctly configured");
        return 400;
    }

    return status;
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

private HttpResponse executeHttpMethod(HttpMethod method) throws HttpException, IOException {
    HttpResponse response = new HttpResponse();
    String responseHeader = null;

    response.setResponseCode(httpClient.executeMethod(method));
    try {//  w  ww. j av a2  s .  c  o m
        responseHeader = method.getResponseHeader(Constants.CONTENT_TYPE).getValue();
    } catch (NullPointerException e) {
        logger.debug("ResponseHeader was null");
    }

    if (responseHeader != null)
        response.setContentType(responseHeader);
    //    response.setResponseBody(method.getResponseBody());
    response.setResponseHeaders(method.getResponseHeaders());
    response.setResponseStatusLine(response.getResponseStatusLine());
    Header contentLength = method.getResponseHeader(Constants.CONTENT_LENGTH);
    if (contentLength != null)
        response.setContentLength(contentLength.getValue());

    if (response.getContentLength() > -1) {
        InputStream stream = null;
        byte[] body = new byte[response.getContentLength()];
        try {
            stream = method.getResponseBodyAsStream();

            int offset = 0;
            int i = -1;
            while ((i = stream.read(body, offset, 1024)) != -1)
                offset += i;
            response.setResponseBody(body);
        } catch (Exception e) {
            logger.error("Could not read entire response body", e);
        } finally {
            if (stream != null)
                stream.close();
        }
    } else {
        logger.debug("Content-length unknown");

        InputStream stream = null;
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        try {
            stream = method.getResponseBodyAsStream();

            int i = -1;
            while ((i = stream.read()) != -1)
                body.write(i);

            response.setResponseBody(body.toByteArray());
            response.setContentLength(body.size());
        } catch (Exception e) {
            logger.error("Could not read entire response body", e);
        } finally {
            body.close();
            if (stream != null)
                stream.close();
        }
    }

    return response;
}

From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java

private SyndFeed retrieveFeed(final String urlStr, final HttpMethod method)
        throws IOException, HttpException, FetcherException, FeedException {

    final Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");

    final InputStream stream;
    if (contentEncodingHeader != null && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
        stream = new GZIPInputStream(method.getResponseBodyAsStream());
    } else {//from www.jav a 2 s  . c  om
        stream = method.getResponseBodyAsStream();
    }

    try {

        final Header contentTypeHeader = method.getResponseHeader("Content-Type");

        final XmlReader reader;
        if (contentTypeHeader != null) {
            reader = new XmlReader(stream, contentTypeHeader.getValue(), true);
        } else {
            reader = new XmlReader(stream, true);
        }

        final SyndFeedInput syndFeedInput = new SyndFeedInput();
        syndFeedInput.setPreserveWireFeed(isPreserveWireFeed());

        return syndFeedInput.build(reader);

    } finally {

        IO.close(stream);

    }

}