Example usage for org.apache.commons.httpclient HttpMethodBase getResponseHeaders

List of usage examples for org.apache.commons.httpclient HttpMethodBase getResponseHeaders

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase getResponseHeaders.

Prototype

@Override
public Header[] getResponseHeaders() 

Source Link

Document

Returns an array of the response headers that the HTTP method currently has in the order in which they were read.

Usage

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back
 * from the SOAP server//  w  ww.  ja  v  a2s  .  c  o  m
 * 
 * @param msgContext
 *            the messsage context
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    //      if (log.isDebugEnabled()) {
    //         log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    //      }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase 
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        //         String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            //            String statusMessage = method.getStatusText();
            //            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            try {
                //               fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$
                //                     method.getResponseBodyAsString()));
                //               fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                //               throw fault;
                throw AxisHttpFault.makeFault(method);
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases 
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else if (contentEncoding.getValue().equals("") //$NON-NLS-1$
                    && msgContext.isPropertyTrue(SoapHttpSender.ALLOW_EMPTY_CONTENT_ENCODING)) {
                // assume no encoding
            } else {
                AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" //$NON-NLS-1$ //$NON-NLS-2$
                        + contentEncoding.getValue() + "' found", null, null); //$NON-NLS-1$
                throw fault;
            }

        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (Header responseHeader : responseHeaders) {
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        //         if (log.isDebugEnabled()) {
        //            if (null == contentLength) {
        //               log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
        //            }
        //            log.debug("\n" + Messages.getMessage("xmlRecd00"));
        //            log.debug("-----------------------------------------------");
        //            log.debug(outMsg.getSOAPPartAsString());
        //         }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (Header header : headers) {
                if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, header.getValue(), msgContext);
                } else if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, header.getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) { //$NON-NLS-1$
            method.releaseConnection();
        }

    } catch (Exception e) {
        //         log.debug(e);
        throw AxisFault.makeFault(e);
    }

    //      if (log.isDebugEnabled()) {
    //         log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    //      }
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Creates new object and fills it with retrieved URL information.
 * //from w  ww.jav  a2  s  .  c om
 * @param http
 *          HTTP protocol options HTTP to retrieve
 * @param filterProcessor
 *          filters to perform
 * @param urlString
 *          the url string
 * 
 * @throws IOException
 *           if error while retrieving URL occur
 */
public HttpResponse(HttpBase http, String urlString, FilterProcessor filterProcessor) throws IOException {
    _http = http;
    _urlString = urlString;
    HttpMethodBase httpMethod = null;
    try {
        httpMethod = getHttpMethod();
        setHttpParameters(http, httpMethod);
        _statusCode = Http.getClient().executeMethod(httpMethod);
        final Header[] headers = httpMethod.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            _headers.set(headers[i].getName(), headers[i].getValue());
        }
        // Content-Type filter should go here
        // TODO: Guess content type when Content-Type header is empty
        boolean contentTypeMatches = true;
        final String contentType = _headers.get(Response.CONTENT_TYPE);
        if ((contentType != null) && (filterProcessor != null)) {
            contentTypeMatches = filterProcessor.evaluateContentTypeFilters(contentType);
            LOG.debug("Content type header: " + contentType + ", passed filters: " + contentTypeMatches);
        }
        if (contentTypeMatches) {
            // always read content. Sometimes content is useful to find a cause for error.
            try {
                final InputStream in = httpMethod.getResponseBodyAsStream();
                if (in != null) {
                    final byte[] buffer = new byte[HttpBase.BUFFER_SIZE];
                    int totalRead = 0;
                    final ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int tryAndRead = calculateTryToRead(totalRead);
                    int bufferFilled = in.read(buffer, 0, buffer.length);
                    while (bufferFilled != -1 && tryAndRead > 0) {
                        totalRead += bufferFilled;
                        out.write(buffer, 0, bufferFilled);
                        tryAndRead = calculateTryToRead(totalRead);
                        bufferFilled = in.read(buffer, 0, buffer.length);
                    }
                    _content = out.toByteArray();
                    in.close();
                }
            } catch (HttpException exception) {
                LOG.error("Http error occured ", exception);
                throw new IOException(exception.toString());
            } catch (IOException exception) {
                if (_statusCode == HttpResponseCode.CODE_200) {
                    throw new IOException(exception.toString());
                }
                // for codes other than 200 OK, we are fine with empty content
            }
            if (_content != null) {
                // check if we have to uncompress it
                final String contentEncoding = _headers.get(Response.CONTENT_ENCODING);
                if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
                if (("application/x-gzip".equals(contentType)) || ("application/gzip".equals(contentType))) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
            }
        } else {
            // URL wasn't fetched
            _statusCode = -1;
        }
    } catch (ProtocolException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } catch (URISyntaxException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

private void setupReceivedData(HttpMethodBase httpMethod, byte[] response) {
    receivedData = httpMethod.getStatusText() + "\r\r";

    for (Header h : httpMethod.getResponseHeaders())
        receivedData += h;//from   w  ww . ja v  a  2  s.  c  o  m

    receivedData += "\r\n";

    try {
        if (response != null)
            receivedData += new String(response, "UTF8");
    } catch (UnsupportedEncodingException e) {
        // TODO what's this ?
    }
}

From source file:org.fao.oaipmh.requests.Transport.java

private void setupReceivedData(HttpMethodBase httpMethod, byte[] response) {
    receivedData = httpMethod.getStatusText() + "\r\r";

    for (Header h : httpMethod.getResponseHeaders())
        receivedData += h;//  w ww  .j  a va  2 s  . c  om

    receivedData += "\r\n";

    try {
        if (response != null)
            receivedData += new String(response, "UTF8");
    } catch (UnsupportedEncodingException e) {
    }
}

From source file:org.httpobjects.proxy.Proxy.java

protected List<HeaderField> extractResponseHeaders(HttpMethodBase method) {
    List<HeaderField> headersReturned = new ArrayList<HeaderField>();
    for (Header h : method.getResponseHeaders()) {
        log.debug("Found header: " + h.getName() + "=" + h.getValue());
        String name = h.getName();
        String value = h.getValue();
        if (name.equals("Set-Cookie")) {
            SetCookieField setCookieField = SetCookieField.fromHeaderValue(value);
            log.debug("Cookie found: " + setCookieField);
            headersReturned.add(setCookieField);
        } else if (name.equals("Location")) {
            String a = processRedirect(value);
            log.debug("Redirecting to " + a);
            headersReturned.add(new LocationField(a));
        } else {//from  w ww  .  ja  v a 2  s . c om
            headersReturned.add(new GenericHeaderField(name, value));
        }
    }
    return headersReturned;
}

From source file:org.jboss.soa.esb.actions.http.HttpAction.java

public Message process(final Message msg) throws ActionProcessingException {

    try {//from ww w .j  ava2s . com
        final HttpClient client = new HttpClient();

        final Properties props = msg.getProperties();

        final String[] names = props.getNames();

        if (METHOD_DELETE.equals(method)) {
            final HttpMethodBase req = new DeleteMethod(uri);

            for (int i = 0; i < names.length; i++) {
                final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]);

                if (headerMatcher.find())
                    req.addRequestHeader(headerMatcher.group(1),
                            (String) props.getProperty(headerMatcher.group()));

            }

            client.executeMethod(req);

            final Header[] headers = req.getResponseHeaders();

            for (int i = 0; i < headers.length; i++)
                props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

            proxy.setPayload(msg, req.getResponseBodyAsString());
        } else if (METHOD_GET.equals(method)) {
            final HttpMethodBase req = new GetMethod(uri);

            final List<NameValuePair> paramList = new ArrayList<NameValuePair>();

            for (int i = 0; i < names.length; i++) {
                final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]);

                if (headerMatcher.find()) {
                    req.addRequestHeader(headerMatcher.group(1),
                            (String) props.getProperty(headerMatcher.group()));

                    continue;
                }

                final Matcher paramMatcher = PATTERN_PARAM.matcher(names[i]);

                if (paramMatcher.find())
                    paramList.add(new NameValuePair(paramMatcher.group(1),
                            (String) props.getProperty(paramMatcher.group())));

            }

            req.setQueryString(paramList.toArray(new NameValuePair[] {}));

            client.executeMethod(req);

            final Header[] headers = req.getResponseHeaders();

            for (int i = 0; i < headers.length; i++)
                props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

            proxy.setPayload(msg, req.getResponseBodyAsString());
        } else if (METHOD_POST.equals(method)) {
            final PostMethod req = new PostMethod(uri);

            for (int i = 0; i < names.length; i++) {
                final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]);

                if (headerMatcher.find()) {
                    req.addRequestHeader(headerMatcher.group(1),
                            (String) props.getProperty(headerMatcher.group()));

                    continue;
                }

                final Matcher paramMatcher = PATTERN_PARAM.matcher(names[i]);

                if (paramMatcher.find())
                    req.addParameter(new NameValuePair(paramMatcher.group(1),
                            (String) props.getProperty(paramMatcher.group())));

            }

            req.setRequestEntity(new StringRequestEntity((String) proxy.getPayload(msg), null, null));

            client.executeMethod(req);

            final Header[] headers = req.getResponseHeaders();

            for (int i = 0; i < headers.length; i++)
                props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

            proxy.setPayload(msg, req.getResponseBodyAsString());
        } else if (METHOD_PUT.equals(method)) {
            final EntityEnclosingMethod req = new PutMethod(uri);

            for (int i = 0; i < names.length; i++) {
                final Matcher headerMatcher = PATTERN_HEADER.matcher(names[i]);

                if (headerMatcher.find())
                    req.addRequestHeader(headerMatcher.group(1),
                            (String) props.getProperty(headerMatcher.group()));

            }

            req.setRequestEntity(new StringRequestEntity((String) proxy.getPayload(msg), null, null));

            client.executeMethod(req);

            final Header[] headers = req.getResponseHeaders();

            for (int i = 0; i < headers.length; i++)
                props.setProperty(PREFIX_HEADER + headers[i].getName(), headers[i].getValue());

            proxy.setPayload(msg, req.getResponseBodyAsString());
        }

    } catch (final Exception e) {
        throw new ActionProcessingException("Can't process message", e);
    }

    return msg;
}

From source file:org.openlaszlo.utils.LZHttpUtils.java

/** Pull response headers from method and put into 
 * servlet response object.//from w w  w.  j a  va  2s  .  c  o  m
 *
 * @param method method to proxy from
 * @param res http servlet response object to proxy to
 * @param isSecure true if get method is secure
 */
static public void proxyResponseHeaders(HttpMethodBase meth, HttpServletResponse res, boolean isSecure) {
    mLogger.debug("proxyResponseHeaders");

    Header[] hedz = meth.getResponseHeaders();

    for (int i = 0; i < hedz.length; i++) {
        String name = hedz[i].getName();
        String value = hedz[i].getValue();
        // Content length passed back to swf app will be different
        if (allowForward(name, null)) {
            // Don't send no-cache headers request is SSL; IE 6 has
            // problems.
            if (isSecure) {
                if (name.equals("Pragma") && value.equals("no-cache"))
                    continue;
                if (name.equals("Cache-Control") && value.equals("no-cache"))
                    continue;
            }

            mLogger.debug("  " + name + "=" + value);

            try {
                if (name.equals("Date") || name.equals("Server")) {
                    res.setHeader(name, value);
                } else {
                    res.addHeader(name, value);
                }
            } catch (Exception e) {
                mLogger.error(
                        /* (non-Javadoc)
                         * @i18n.test
                         * @org-mes="Exception when proxying a response header: " + p[0]
                         */
                        org.openlaszlo.i18n.LaszloMessages.getMessage(LZHttpUtils.class.getName(), "051018-304",
                                new Object[] { e.getMessage() }));
            }
        }
    }
}

From source file:org.springfield.mojo.http.HttpHelper.java

/**
 * Sends a standard HTTP request to the specified URI using the determined method.
 * Attaches the content, uses the specified content type, sets cookies, timeout and
 * request headers/*w  w w  .  ja  v a2s.  c o  m*/
 *  
 * @param method - the request method
 * @param uri - the uri to request
 * @param body - the content  
 * @param contentType - the content type
 * @param cookies - cookies
 * @param timeout - timeout in milliseconds
 * @param charSet - the character set
 * @param requestHeaders - extra user defined headers
 * @return response
 */
public static Response sendRequest(String method, String uri, String body, String contentType, String cookies,
        int timeout, String charSet, Map<String, String> requestHeaders) {
    // http client
    HttpClient client = new HttpClient();

    // method
    HttpMethodBase reqMethod = null;
    if (method.equals(HttpMethods.PUT)) {
        reqMethod = new PutMethod(uri);
    } else if (method.equals(HttpMethods.POST)) {
        reqMethod = new PostMethod(uri);
    } else if (method.equals(HttpMethods.GET)) {
        if (body != null) {
            // hack to be able to send a request body with a get (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "GET";
                }
            };
        } else {
            reqMethod = new GetMethod(uri);
        }
    } else if (method.equals(HttpMethods.DELETE)) {
        if (body != null) {
            // hack to be able to send a request body with a delete (only if required)
            reqMethod = new PostMethod(uri) {
                public String getName() {
                    return "DELETE";
                }
            };
        } else {
            reqMethod = new DeleteMethod(uri);
        }
    } else if (method.equals(HttpMethods.HEAD)) {
        reqMethod = new HeadMethod(uri);
    } else if (method.equals(HttpMethods.TRACE)) {
        reqMethod = new TraceMethod(uri);
    } else if (method.equals(HttpMethods.OPTIONS)) {
        reqMethod = new OptionsMethod(uri);
    }

    // add request body
    if (body != null) {
        try {
            RequestEntity entity = new StringRequestEntity(body, contentType, charSet);
            ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity);
            reqMethod.setRequestHeader("Content-type", contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // add cookies
    if (cookies != null) {
        reqMethod.addRequestHeader("Cookie", cookies);
    }

    // add custom headers
    if (requestHeaders != null) {
        for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
            String name = header.getKey();
            String value = header.getValue();

            reqMethod.addRequestHeader(name, value);
        }
    }

    Response response = new Response();

    // do request
    try {
        if (timeout != -1) {
            client.getParams().setSoTimeout(timeout);
        }
        int statusCode = client.executeMethod(reqMethod);
        response.setStatusCode(statusCode);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // read response
    try {
        InputStream instream = reqMethod.getResponseBodyAsStream();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int len;
        while ((len = instream.read(buffer)) > 0) {
            outstream.write(buffer, 0, len);
        }
        String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet());
        response.setResponse(resp);

        //set content length
        long contentLength = reqMethod.getResponseContentLength();
        response.setContentLength(contentLength);
        //set character set
        String respCharSet = reqMethod.getResponseCharSet();
        response.setCharSet(respCharSet);
        //set all headers
        Header[] headers = reqMethod.getResponseHeaders();
        response.setHeaders(headers);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // release connection
    reqMethod.releaseConnection();

    // return
    return response;
}