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

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

Introduction

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

Prototype

public abstract String getStatusText();

Source Link

Usage

From source file:org.sonatype.nexus.integrationtests.nexus3233.Nexus3233IndexPomSha1IT.java

@Test
@Category(INDEX.class)
public void restDeploy() throws Exception {
    final File pom = getTestFile("rest.pom");
    HttpMethod r = getDeployUtils().deployPomWithRest(REPO_TEST_HARNESS_REPO, pom);
    Assert.assertTrue("Unable to deploy artifact " + r.getStatusCode() + ": " + r.getStatusText(),
            Status.isSuccess(r.getStatusCode()));
    searchFor(pom);/*from  ww  w .j  a  va 2s  .co m*/
}

From source file:org.springbyexample.httpclient.AbstractHttpClientTemplate.java

/**
 * Validate response.//w  w w . j  ava  2 s  . co  m
 * 
 * @param   httpMethod      <code>HttpMethod</code> to validate.
 */
protected void validateResponse(HttpMethod httpMethod) {
    if (httpMethod.getStatusCode() >= 300) {
        throw new HttpAccessException(
                "Did not receive successful HTTP response: status code = " + httpMethod.getStatusCode()
                        + ", status message = [" + httpMethod.getStatusText() + "]",
                httpMethod.getStatusCode());
    }
}

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 . java 2s . c o m*/

    //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.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.HttpCommand.java

private SimpleHttpResponse toResponse(HttpMethod method) {
    SimpleHttpResponse response;//from  www. ja  v a2  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.xwiki.test.rest.framework.AbstractHttpTest.java

protected String getHttpMethodInfo(HttpMethod method) throws Exception {
    return String.format("\nName: %s\nURI: %s\nStatus code: %d\nStatus text: %s", method.getName(),
            method.getURI(), method.getStatusCode(), method.getStatusText());
}

From source file:smartrics.rest.client.RestClientImpl.java

/**
 * See {@link smartrics.rest.client.RestClient#execute(java.lang.String, smartrics.rest.client.RestRequest)}
 *//*from ww w.j  a v a 2s.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  w w w .j  av a 2 s  .co  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 a2s  .c o  m*/
 * @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/*from   www.j av  a  2 s  . 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;
}