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:smartrics.rest.client.RestClientImpl.java

/**
 * See {@link smartrics.rest.client.RestClient#execute(java.lang.String, smartrics.rest.client.RestRequest)}
 *///from w w  w .  java2s. c om
public RestResponse execute(String hostAddr, final RestRequest request) {
    if (request == null || !request.isValid())
        throw new IllegalArgumentException("Invalid request " + request);
    if (request.getTransactionId() == null)
        request.setTransactionId(Long.valueOf(System.currentTimeMillis()));
    LOG.debug("request: {}", request);
    HttpMethod m = createHttpClientMethod(request);
    configureHttpMethod(m, hostAddr, request);
    RestResponse resp = new RestResponse();
    resp.setTransactionId(request.getTransactionId());
    resp.setResource(request.getResource());
    try {
        client.executeMethod(m);
        for (Header h : m.getResponseHeaders()) {
            resp.addHeader(h.getName(), h.getValue());
        }
        resp.setStatusCode(m.getStatusCode());
        resp.setStatusText(m.getStatusText());
        resp.setBody(m.getResponseBodyAsString());
        resp.setRawBody(m.getResponseBody());
    } catch (HttpException e) {
        String message = "Http call failed for protocol failure";
        throw new IllegalStateException(message, e);
    } catch (IOException e) {
        String message = "Http call failed for IO failure";
        throw new IllegalStateException(message, e);
    } finally {
        m.releaseConnection();
    }
    LOG.debug("response: {}", resp);
    return resp;
}

From source file:smilehouse.opensyncro.defaultcomponents.http.HTTPUtils.java

/**
 * Makes a HTTP request to the specified url with a set of parameters,
  * request method, user name and password
 * /*from   ww w  .ja v  a  2  s  .c o  m*/
 * @param url the <code>URL</code> to make a request to 
 * @param method either "GET", "POST", "PUT" or "SOAP"
 * @param parameters two dimensional string array containing parameters to send in the request
 * @param user user name to submit in the request 
 * @param password password to submit in the request
 * @param charsetName charset name used for message content encoding
  * @param responseCharsetName charset name used to decode HTTP responses,
  *                            or null to use default ("ISO-8859-1")
  * @param contentType Content-Type header value (without charset information)
  *                    for POST (and SOAP) type requests. If null, defaults to
  *                    "text/xml".
 * @return a string array containing the body of the response, the headers of
  *         the response and possible error message
 * @throws Exception 
 */
public static HTTPResponse makeRequest(URL url, String method, String[][] parameters, String user,
        String password, String charsetName, String responseCharsetName, String contentType) throws Exception {

    HttpClient httpclient = new HttpClient();

    HttpMethod request_method = null;
    HTTPResponse responseData = new HTTPResponse();
    NameValuePair[] names_values = null;

    String requestContentType;
    if (contentType != null && contentType.length() > 0) {
        requestContentType = contentType;
    } else {
        requestContentType = DEFAULT_CONTENT_TYPE;
    }

    if (parameters != null && method.equals("PUT") == false) {
        names_values = new NameValuePair[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            names_values[i] = new NameValuePair(parameters[i][0], parameters[i][1]);
        }

    }
    if (method.equalsIgnoreCase("POST")) {
        request_method = new PostMethod(url.toString());
        if (names_values != null)
            ((PostMethod) request_method).setRequestBody(names_values);
    } else if (method.equalsIgnoreCase("PUT")) {
        if (parameters == null)
            throw new Exception("No data to use in PUT request");
        request_method = new PutMethod(url.toString());
        StringRequestEntity sre = new StringRequestEntity(parameters[0][0]);
        ((PutMethod) request_method).setRequestEntity(sre);
    } else if (method.equalsIgnoreCase("SOAP")) {
        String urlString = url.toString() + "?";
        String message = null;
        String action = null;
        for (int i = 0; i < parameters.length; i++) {

            if (parameters[i][0].equals(SOAPMESSAGE))
                message = parameters[i][1];
            else if (parameters[i][0].equals(SOAP_ACTION_HEADER))
                action = parameters[i][1];
            else
                urlString += parameters[i][0] + "=" + parameters[i][1] + "&";
        }
        urlString = urlString.substring(0, urlString.length() - 1);
        request_method = new PostMethod(urlString);
        // Encoding content with requested charset 
        StringRequestEntity sre = new StringRequestEntity(message, requestContentType, charsetName);
        ((PostMethod) request_method).setRequestEntity(sre);
        if (action != null) {
            request_method.setRequestHeader(SOAP_ACTION_HEADER, action);
        }
        // Adding charset also into header's Content-Type
        request_method.addRequestHeader(CONTENT_TYPE_HEADER, requestContentType + "; charset=" + charsetName);
    } else {
        request_method = new GetMethod(url.toString());
        if (names_values != null)
            ((GetMethod) request_method).setQueryString(names_values);
    }

    user = (user == null || user.length() < 1) ? null : user;
    password = (password == null || password.length() < 1) ? null : password;

    if ((user != null & password == null) || (user == null & password != null)) {
        throw new Exception("Invalid username or password");

    }
    if (user != null && password != null) {
        httpclient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
        httpclient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                defaultcreds);
        request_method.setDoAuthentication(true);
    }

    try {
        httpclient.executeMethod(request_method);

        if (request_method.getStatusCode() != HttpStatus.SC_OK) {
            responseData
                    .setResponseError(request_method.getStatusCode() + " " + request_method.getStatusText());
        }

        //Write response header to the out string array
        Header[] headers = request_method.getResponseHeaders();
        responseData.appendToHeaders("\nHTTP status " + request_method.getStatusCode() + "\n");
        for (int i = 0; i < headers.length; i++) {
            responseData.appendToHeaders(headers[i].getName() + ": " + headers[i].getValue() + "\n");
        }

        /*
         * TODO: By default, the response charset should be read from the Content-Type header of 
         * the response and that should be used in the InputStreamReader constructor: 
         * 
         * <code>new InputStreamReader(request_method.getResponseBodyAsStream(), 
         *                   ((HttpMethodBase)request_method).getResponseCharSet());</code>
         * 
         * But for backwards compatibility, the charset used by default is now the one that the 
         * HttpClient library chooses (ISO-8859-1). An alternative charset can be chosen, but in 
         * no situation is the charset read from the response's Content-Type header.
         */
        BufferedReader br = null;
        if (responseCharsetName != null) {
            br = new BufferedReader(
                    new InputStreamReader(request_method.getResponseBodyAsStream(), responseCharsetName));
        } else {
            br = new BufferedReader(new InputStreamReader(request_method.getResponseBodyAsStream()));
        }

        String responseline;
        //Write response body to the out string array
        while ((responseline = br.readLine()) != null) {
            responseData.appendToBody(responseline + "\n");
        }
    } finally {
        request_method.releaseConnection();
    }
    return responseData;
}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Runs a WEBDAV command//from   w w  w  .j a  v  a 2  s . com
 * @param client The HTTP client transport to use
 * @param method The method to be executed
 * @return True/False based on execution
 * @throws IOException
 */
public static boolean executeMethod(HttpClient client, HttpMethod method) throws IOException {
    client.executeMethod(method);
    int statusCode = method.getStatusCode();
    logger.trace("executeMethod - statusCode - " + statusCode);

    boolean result = method.getStatusCode() == HttpURLConnection.HTTP_OK;
    logger.debug("executeMethod - result - " + result);
    logger.debug(method.getStatusCode() + " " + method.getStatusText() + " " + method.getResponseBodyAsString()
            + " " + Arrays.toString(method.getResponseHeaders()));

    return result;
}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Used for checking if a file exists/* w w  w  .j  a  v  a 2s  . c  o m*/
 * @param client    The client to execute the method
 * @param method    The method to be executed
 * @param ignoreHTTPNOTFOUND  Used to flag if the HTTP_NOT_FOUND error has to be ignored, if not the IOException raised will be thrown
 * @return  Returns if the execution has been successful
 * @throws IOException
 */
public static boolean executeMethod(HttpClient client, HttpMethod method, boolean ignoreHTTPNOTFOUND)
        throws IOException {
    try {
        client.executeMethod(method);
    } catch (IOException e) {
        //If it is not 404 - throw exception, otherwise
        if (method.getStatusCode() != HttpURLConnection.HTTP_NOT_FOUND)
            throw e;
    }
    int statusCode = method.getStatusCode();
    logger.trace("executeMethod - statusCode - " + statusCode);

    boolean result = (method.getStatusCode() == HttpURLConnection.HTTP_OK);
    logger.debug("executeMethod - result - " + result);
    logger.debug(method.getStatusCode() + " " + method.getStatusText() + " " + method.getResponseBodyAsString()
            + " " + Arrays.toString(method.getResponseHeaders()));

    return result;
}