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:ch.lipsch.subsonic4j.internal.SubsonicServiceImpl.java

private void fetchAsyncStream(String url, final StreamListener listener)
        throws IOException, JAXBException, SubsonicException {
    final HttpMethod method = new GetMethod(url);
    httpClient.executeMethod(method);/*  w w w . ja v a  2  s.  c o  m*/

    final InputStream responseStream = method.getResponseBodyAsStream();
    Header contentTypeHeader = method.getResponseHeader(HTTP_RESPONSE_HEADER_CONTENT_TYPE);

    if (contentTypeHeader.getValue().startsWith(HTTP_CONTENT_TYPE_TEXT_XML)) {
        // There was an error
        Response response = unmarshalResponse(responseStream);
        SubsonicUtil.throwExceptionIfNecessary(response);
    } else {
        new Thread("StreamDeliverer") {
            @Override
            public void run() {
                try {
                    listener.receivedStream(responseStream);
                } finally {
                    method.releaseConnection();
                }
            };
        }.start();
    }
}

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  w w  .  ja v a  2s.  co 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, String alternativeHeaderName)
        throws HttpException {
    Header header = method.getResponseHeader(headerName);
    if (header == null || header.getValues().length != 1)
        header = method.getResponseHeader(alternativeHeaderName);
    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:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    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.  java  2s .c o m
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // 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(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                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);
            result.addStatus(status);
            redirectionsCount++;

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

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

public List<FreeBusy> getFreeBusyForHost(String host, ArrayList<Request> req) throws IOException {
    ArrayList<FreeBusy> ret = new ArrayList<FreeBusy>();
    int fb_interval = LC.exchange_free_busy_interval_min.intValueWithinRange(5, 1444);
    Request r = req.get(0);/*from ww w.  j  ava2s  .c om*/
    ServerInfo serverInfo = (ServerInfo) r.data;
    if (serverInfo == null) {
        ZimbraLog.fb.warn("no exchange server info for user " + r.email);
        return ret;
    }
    if (!serverInfo.enabled) {
        return ret;
    }
    String url = constructGetUrl(serverInfo, req);
    ZimbraLog.fb.debug("fetching fb from url=" + url);
    HttpMethod method = new GetMethod(url);

    Element response = null;
    try {
        int status = sendRequest(method, serverInfo);
        if (status != 200)
            return getEmptyList(req);
        if (ZimbraLog.fb.isDebugEnabled()) {
            Header cl = method.getResponseHeader("Content-Length");
            int contentLength = 10240;
            if (cl != null)
                contentLength = Integer.valueOf(cl.getValue());
            String buf = new String(com.zimbra.common.util.ByteUtil.readInput(method.getResponseBodyAsStream(),
                    contentLength, contentLength), "UTF-8");
            ZimbraLog.fb.debug(buf);
            response = Element.parseXML(buf);
        } else
            response = Element.parseXML(method.getResponseBodyAsStream());
    } catch (XmlParseException e) {
        ZimbraLog.fb.warn("error parsing fb response from exchange", e);
        return getEmptyList(req);
    } catch (IOException e) {
        ZimbraLog.fb.warn("error parsing fb response from exchange", e);
        return getEmptyList(req);
    } finally {
        method.releaseConnection();
    }
    for (Request re : req) {
        String fb = getFbString(response, re.email);
        ret.add(new ExchangeUserFreeBusy(fb, re.email, fb_interval, re.start, re.end));
    }
    return ret;
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);//www.  j  a v  a 2  s  .  c o  m
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}

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

/**
 * HEAD methods return an empty response body. If a HEAD request populates
 * a cache and then a GET follorws, a blank page will result.
 * This test ensures that the SimplePageCachingFilter implements calculateKey
 * properly to avoid this problem.//from  w  w w .  j a  v  a 2  s. com
 */
public void testHeadThenGetOnCachedPage() throws Exception {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new HeadMethod(buildUrl(cachedPageUrl));
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));

    httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    responseCode = httpClient.executeMethod(httpMethod);
    responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);

}

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

/**
 * When the servlet container generates a 404 page not found, we want to pass
 * it through without caching and without adding anything to it.
 * <p/>/*from   ww  w .j a va  2  s.com*/
 * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/SendRedirect.jsp
 */
public void testRedirect() throws Exception {

    String url = "http://localhost:9080/non_ok/SendRedirect.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
}

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

/**
 * When the servlet container generates a 404 page not found, we want to pass
 * it through without caching and without adding anything to it.
 * <p/>/* www  . j  a v a2 s . c  om*/
 * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/PageNotFound.jsp
 */
public void testNotFound() throws Exception {

    String url = "http://localhost:9080/non_ok/PageNotFound.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
}

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

/**
 * Servlets and JSPs can send content even when the response is set to no content.
 * In this case there should not be a body but there is. Orion seems to kill the body
 * after is has left the Servlet filter chain. To avoid wget going into an inifinite
 * retry loop, and presumably some other web clients, the content length should be 0
 * and the body 0.//from  www. j  ava 2s . c o m
 * <p/>
 * Manual Test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_caching_filter/SC_NO_CONTENT.jsp
 */
public void testNoContentJSPGzipFilter() throws Exception {

    String url = "http://localhost:9080/empty_caching_filter/SC_NO_CONTENT.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);

}

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

/**
 * Servlets and JSPs can send content even when the response is set to no content.
 * In this case there should not be a body but there is. Orion seems to kill the body
 * after is has left the Servlet filter chain. To avoid wget going into an inifinite
 * retry loop, and presumably some other web clients, the content length should be 0
 * and the body 0.//from   w  w  w .j a va  2  s .c o m
 * <p/>
 * wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9080/empty_caching_filter/SC_NOT_MODIFIED.jsp
 */
public void testNotModifiedJSPGzipFilter() throws Exception {

    String url = "http://localhost:9080/empty_caching_filter/SC_NOT_MODIFIED.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NOT_MODIFIED, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);

}