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:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {//from   ww w  .j  a  va  2s  . c  om
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;

    try {/*  w  w  w .  ja v a 2s.c  o  m*/
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

        if (location == null) {
            return byteArray;
        } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) {

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }//from w ww  .  j  a  v a 2s. c o m
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr
                        .lastIndexOf((mCredentials instanceof KeloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:com.owncloud.android.lib.common.OwnCloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*  w  ww  .  j  a v  a 2  s. co  m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

protected void copyResponseHeaders(HttpMethod method, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) {
    for (org.apache.commons.httpclient.Header header : method.getResponseHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName())) {
            continue;
        }/*from   w w w.ja v  a2 s .co m*/
        if (header.getName().equalsIgnoreCase("Content-Length")
                && (method.getResponseHeader("Content-Type") == null
                        || method.getResponseHeader("Content-Type").getValue().contains("html"))) {
            continue;
        }
        if (header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE)
                || header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(servletRequest, servletResponse, header.getValue());
        } else {
            servletResponse.addHeader(header.getName(), header.getValue());
        }
    }
}

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

private SyndFeedInfo buildSyndFeedInfo(final URL feedUrl, final String urlStr, final HttpMethod method,
        SyndFeed feed, final int statusCode) throws MalformedURLException {

    SyndFeedInfo syndFeedInfo;//from  ww  w  . ja  va  2 s  .c o m
    syndFeedInfo = new SyndFeedInfo();

    // this may be different to feedURL because of 3XX redirects
    syndFeedInfo.setUrl(new URL(urlStr));
    syndFeedInfo.setId(feedUrl.toString());

    final Header imHeader = method.getResponseHeader("IM");
    if (imHeader != null && imHeader.getValue().contains("feed") && isUsingDeltaEncoding()) {

        final FeedFetcherCache cache = getFeedInfoCache();

        if (cache != null && statusCode == 226) {
            // client is setup to use http delta encoding and the server supports it and has
            // returned a delta encoded response. This response only includes new items
            final SyndFeedInfo cachedInfo = cache.getFeedInfo(feedUrl);

            if (cachedInfo != null) {
                final SyndFeed cachedFeed = cachedInfo.getSyndFeed();

                // set the new feed to be the orginal feed plus the new items
                feed = combineFeeds(cachedFeed, feed);
            }
        }
    }

    final Header lastModifiedHeader = method.getResponseHeader("Last-Modified");
    if (lastModifiedHeader != null) {
        syndFeedInfo.setLastModified(lastModifiedHeader.getValue());
    }

    final Header eTagHeader = method.getResponseHeader("ETag");
    if (eTagHeader != null) {
        syndFeedInfo.setETag(eTagHeader.getValue());
    }

    syndFeedInfo.setSyndFeed(feed);

    return syndFeedInfo;
}

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

private HttpMethod checkFollowRedirect(final HttpMethod method, final int res)
        throws IOException, HttpClientException {

    if ((res == HttpStatus.SC_MOVED_TEMPORARILY) || (res == HttpStatus.SC_MOVED_PERMANENTLY)
            || (res == HttpStatus.SC_SEE_OTHER) || (res == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        final Header locHeader = method.getResponseHeader("Location");
        if (locHeader == null) {
            throw new HttpClientException("Redirect with no Location header, request URL: " + method.getURI());
        }/*from   w  w  w. ja va 2s .  co  m*/
        final String location = locHeader.getValue();
        logger.debug("Follow redirect: " + res + ": " + location);

        method.releaseConnection();
        final GetMethod followMethod = new GetMethod(location);
        followMethod.setFollowRedirects(true);
        resultCode = httpc.executeMethod(followMethod);
        reasonCode = followMethod.getStatusText();
        logger.debug("Result: " + resultCode);
        return followMethod;
    }
    return method;
}

From source file:net.sf.j2ep.ProxyFilter.java

/**
 * Will create the method and execute it. After this the method
 * is sent to a ResponseHandler that is returned.
 * /*from w w  w  .j  a v a2  s . c o  m*/
 * @param httpRequest Request we are receiving from the client
 * @param url The location we are proxying to
 * @return A ResponseHandler that can be used to write the response
 * @throws MethodNotAllowedException If the method specified by the request isn't handled
 * @throws IOException When there is a problem with the streams
 * @throws HttpException The httpclient can throw HttpExcetion when executing the method
 */
private ResponseHandler executeRequest(HttpServletRequest httpRequest, String url)
        throws MethodNotAllowedException, IOException, HttpException {
    RequestHandler requestHandler = RequestHandlerFactory.createRequestMethod(httpRequest.getMethod());

    HttpMethod method = requestHandler.process(httpRequest, url);
    method.setFollowRedirects(false);

    /*
     * Why does method.validate() return true when the method has been
     * aborted? I mean, if validate returns true the API says that means
     * that the method is ready to be executed. TODO I don't like doing type
     * casting here, see above.
     */
    if (!((HttpMethodBase) method).isAborted()) {
        httpClient.executeMethod(method);

        if (method.getStatusCode() == 405) {
            Header allow = method.getResponseHeader("allow");
            String value = allow.getValue();
            throw new MethodNotAllowedException("Status code 405 from server",
                    AllowedMethodHandler.processAllowHeader(value));
        }
    }

    return ResponseHandlerFactory.createResponseHandler(method);
}

From source file:edu.umd.cs.buildServer.BuildServerDaemon.java

/**
 * Get a required header value. If the header value isn't specified in the
 * server response, returns null.// w ww .  jav a 2s.c o  m
 *
 * @param method
 *            the HttpMethod representing the request/response
 * @param headerName
 *            the name of the header
 * @return the value of the header, or null if the header isn't present
 * @throws HttpException
 */
private String getRequiredHeaderValue(HttpMethod method, String headerName) throws HttpException {
    Header header = method.getResponseHeader(headerName);
    if (header == null || header.getValues().length != 1) {
        getLog().error("Internal error: Missing header " + headerName + " in submit server response");
        for (Header h : method.getResponseHeaders()) {
            getLog().error("  have header " + h.getName());
        }
        return null;
    }
    return header.getValue();
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

@Test
public void testCachingHeadersSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertNotNull(httpMethod.getResponseHeader("Last-Modified"));
    assertNotNull(httpMethod.getResponseHeader("Expires"));
    assertEquals("max-age=3600", httpMethod.getResponseHeader("Cache-Control").getValue());
    assertFalse("this did not get overriden".equals(httpMethod.getResponseHeader("Last-Modified").getValue()));
}