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

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

Introduction

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

Prototype

public abstract Header[] getResponseHeaders();

Source Link

Usage

From source file:org.roosster.RoossterTestCase.java

/**
 * /*from   w  ww . j a v a  2s  .co m*/
 */
public void logMethodResponse(HttpMethod method) throws java.io.IOException {
    if (method == null)
        throw new IllegalArgumentException("FAILED: Tried to log 'null' method");

    if (method.isRequestSent() == false)
        throw new IllegalArgumentException("FAILED: Tried to log 'not-sent' method");

    System.out.println("++++++++++++++++++++++++ BEGIN HEADER LOGGING ++++++++++++++++++++++++");

    StatusLine sline = method.getStatusLine();
    System.out.println("\nStatusLine: " + sline.getHttpVersion() + " " + sline.getStatusCode() + " "
            + sline.getReasonPhrase());

    System.out.println("\nHeader:\n");

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].toString());
    }

    System.out.println("\nResponseBody:\n" + method.getResponseBodyAsString() + "\n\n");

    System.out.println("++++++++++++++++++++++++ END HEADER LOGGING ++++++++++++++++++++++++\n\n");
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * /* w  w w  . j a  v  a  2 s.co m*/
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

From source file:org.sakaiproject.kernel.proxy.ProxyResponseImpl.java

/**
 * @param result/*from   ww w  .  j  ava  2 s  .c o  m*/
 * @param method
 */
public ProxyResponseImpl(int result, HttpMethod method) {
    this.result = result;
    this.method = method;

    for (Header h : method.getResponseHeaders()) {
        String name = h.getName();
        String[] values = headers.get(name);
        if (values == null) {
            values = new String[] { h.getValue() };
        } else {
            String[] newValues = new String[values.length + 1];
            System.arraycopy(values, 0, newValues, 0, values.length);
            newValues[values.length] = h.getValue();
            values = newValues;
        }
        headers.put(name, values);
    }
}

From source file:org.sakaiproject.nakamura.proxy.ProxyResponseImpl.java

/**
 * @param result/*w  w w  .  ja  va2  s.  c  om*/
 * @param method
 */
public ProxyResponseImpl(int result, HttpMethod method) {
    this.result = result;
    this.method = method;

    for (Header header : method.getResponseHeaders()) {
        String name = header.getName();
        String[] values = headers.get(name);
        if (values == null) {
            values = new String[] { header.getValue() };
        } else {
            String[] newValues = new String[values.length + 1];
            System.arraycopy(values, 0, newValues, 0, values.length);
            newValues[values.length] = header.getValue();
            values = newValues;
        }

        boolean add = true;
        // We ignore JSESSIONID cookies coming back.
        if (name.toLowerCase().equals("set-cookie")) {
            for (String v : values) {
                if (v.contains("JSESSIONID")) {
                    add = false;
                    break;
                }
            }
        }
        if (add) {
            headers.put(name, values);
        }
    }
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Execute the supplied HTTP Method.//from  ww w  . j av a  2s.c o m
 * <p/>
 * Does not release the {@link org.apache.commons.httpclient.HttpMethod#releaseConnection() HttpMethod connection}.
 *
 * @param method The HTTP Method.
 * @return The HTTP Response.
 */
public String execute(HttpMethod method) {
    if (_httpClient == null) {
        Assert.fail(
                "HTTPMixIn not initialized.  You must call the initialize() method before using this MixIn");
    }

    for (String key : _requestHeaders.keySet()) {
        method.setRequestHeader(key, _requestHeaders.get(key));
    }

    if (_dumpMessages) {
        for (Header header : method.getRequestHeaders()) {
            _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]");
        }
    }

    String response = null;
    try {
        _httpClient.executeMethod(method);
        response = method.getResponseBodyAsString();
    } catch (Exception e) {
        try {
            Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage());
        } catch (URIException e1) {
            _logger.error("Unexpected error", e1);
            return null;
        }
    }

    if (_dumpMessages) {
        for (Header header : method.getResponseHeaders()) {
            _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]");
        }
        _logger.info("Received response body:[" + response + "]");
    }

    for (String key : _expectedHeaders.keySet()) {
        Header actual = method.getResponseHeader(key);
        Assert.assertNotNull("Checking response header:[" + key + "]", actual);
        Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key),
                actual.getValue());
    }

    return response;
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

private static void setupResponseHeaders(HttpMethod httpMethod, HttpServletResponse hsResponse) {
    if (log.isInfoEnabled()) {
        log.info("setupResponseHeaders");
        log.info("status text: " + httpMethod.getStatusText());
        log.info("status line: " + httpMethod.getStatusLine());
    }/*from w w w  .ja va2  s . c  om*/

    //filter the headers, which are copied from the proxy response. The http lib handles those itself.
    //Filtered out: the content encoding, the content length and cookies
    for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) {
        Header h = httpMethod.getResponseHeaders()[i];
        if ("content-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("content-length".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("transfer-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if (h.getName().toLowerCase().startsWith("cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        } else if (h.getName().toLowerCase().startsWith("set-cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        }

        hsResponse.addHeader(h.getName(), h.getValue());
        if (log.isInfoEnabled())
            log.info("setting response parameter:" + h.getName() + ", value: " + h.getValue());
    }
    //fixme what about the response footers? (httpMethod.getResponseFooters())

    if (httpMethod.getStatusCode() != 200) {
        hsResponse.setStatus(httpMethod.getStatusCode());
    }
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * {@inheritDoc}/*from w w  w . j av  a  2  s.  c  o  m*/
 *
 * @see org.tuleap.mylyn.task.core.internal.client.rest.IRestConnector#sendRequest(org.apache.commons.httpclient.HttpMethod)
 */
@Override
public ServerResponse sendRequest(HttpMethod method) {
    // debug mode
    boolean debug = false;
    IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ITuleapConstants.TULEAP_PREFERENCE_NODE);
    if (node != null) {
        debug = node.getBoolean(ITuleapConstants.TULEAP_PREFERENCE_DEBUG_MODE, false);
    }

    if (hostConfiguration == null) {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, null);
    }

    method.setRequestHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Accept-Charset", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$

    WebUtil.configureHttpClient(httpClient, getUserAgent());

    Header[] responseHeaders = null;
    String responseBody = null;
    ServerResponse serverResponse = null;
    try {
        int code = WebUtil.execute(httpClient, hostConfiguration, method, null);
        responseBody = method.getResponseBodyAsString();
        responseHeaders = method.getResponseHeaders();
        if (debug) {
            debugRestCall(method, responseBody);
        }
        Map<String, String> rHeaders = new LinkedHashMap<String, String>();
        for (Header h : responseHeaders) {
            rHeaders.put(h.getName(), h.getValue());
        }
        serverResponse = new ServerResponse(code, responseBody, rHeaders);
    } catch (IOException e) {
        logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages
                .getString(TuleapCoreKeys.ioError, method.getName() + ' ' + method.getPath(), e.getMessage())));
        serverResponse = new ServerResponse(IO_ERROR_STATUS_CODE, "", Collections //$NON-NLS-1$
                .<String, String>emptyMap());
    } finally {
        method.releaseConnection();
    }

    return serverResponse;
}

From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java

private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) {
    logger.finest("Fetching content using HttpClient....user-Id: " + tokenId);
    HttpClient hc = new HttpClient();
    hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    HttpMethod method = new GetMethod(href);
    method.addRequestHeader("xx-wings-user-id", tokenId);
    ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>();
    Set<String> keys = requestParameters.keySet();
    for (String key : keys) {
        String value = requestParameters.get(key);
        nvpList.add(new NameValuePair(key, value));
    }/*from  w  w w.  j  a  v a 2 s  .  c o m*/

    String qs = method.getQueryString();
    if (qs != null) {
        String[] nvPairs = qs.split("&");
        for (String nvPair : nvPairs) {
            String[] mapping = nvPair.split("=");
            nvpList.add(new NameValuePair(mapping[0], mapping[1]));
        }
    }
    method.setFollowRedirects(true);

    NameValuePair[] nvps = new NameValuePair[nvpList.size()];
    nvps = nvpList.toArray(nvps);
    method.setQueryString(nvps);

    byte[] content = null;
    Header[] headers = null;
    try {
        hc.executeMethod(method);
        content = method.getResponseBody();
        headers = method.getResponseHeaders();
    } catch (HttpException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
    return new Response(content, headers);
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.HttpCommand.java

private SimpleHttpResponse toResponse(HttpMethod method) {
    SimpleHttpResponse response;/*from www.  ja  v a  2 s.  c  o m*/
    Header[] headers = method.getResponseHeaders();
    String headersString = "";
    for (Header header : headers) {
        headersString += header.toString();
    }
    try {
        response = new SimpleHttpResponse(method.getStatusCode(), method.getStatusText(), headersString,
                method.getResponseBodyAsString());
    } catch (Exception e) {
        throw new RuntimeException("", e);
    }
    return response;
}

From source file:org.wso2.carbon.remotetasks.core.RemoteTask.java

@Override
public void execute() {
    boolean systemTask = this.isSystemTask();
    if (!systemTask) {
        this.notifyTaskManager();
    }/*from w  ww .j  a  va2  s  . c  om*/
    String targetURI = this.getProperties().get(RemoteTasksConstants.REMOTE_TASK_URI);
    if (targetURI == null || targetURI.length() == 0) {
        return;
    }
    HttpClient client = new HttpClient();
    client.getParams().setSoTimeout(DEFAULT_CONNECTION_TIMEOUT);
    HttpMethod method = new GetMethod(targetURI);
    if (systemTask) {
        method.setRequestHeader(RemoteTasksConstants.REMOTE_SYSTEM_TASK_HEADER_ID,
                this.getProperties().get(RemoteTasksConstants.REMOTE_SYSTEM_TASK_ID));
    }
    try {
        if (log.isDebugEnabled()) {
            log.debug("Executing remote task to URI: " + targetURI);
        }
        client.executeMethod(method);
        if (log.isDebugEnabled()) {
            StringBuilder builder = new StringBuilder();
            builder.append("Response Headers:-\n");
            for (Header header : method.getResponseHeaders()) {
                builder.append("\t" + header.getName() + ": " + header.getValue() + "\n");
            }
            log.debug(builder.toString());
        }
        String body = method.getResponseBodyAsString();
        if (log.isDebugEnabled()) {
            log.debug("Response Body:-\n\t" + body);
        }
        method.releaseConnection();
    } catch (Exception e) {
        log.error("Error executing remote task: " + e.getMessage(), e);
    }
}