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

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

Introduction

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

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * Open an HTTP GET method connection to a URL and read the returned response into an
 * object./*from  w  w w  . jav  a 2s.  c o  m*/
 * 
 * @param url
 *            remote URL (usually a web service's URL)
 * @param httpMethod
 *            HTTP method
 * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the
 *         response headers and body
 */
public static HttpResponseTo getHttpResponse(final String url, final HttpMethod method) {
    if (log.isDebugEnabled()) {
        log.debug("Sending HTTP " + method + " request to " + url);
    }

    // Create an instance of HttpClient.
    final HttpClient client = new HttpClient();

    // Create a method instance.
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false));
    try {
        // Execute the method
        final int statusCode = client.executeMethod(method);
        if (statusCode >= 400) {
            log.error("Method failed: " + method.getStatusLine());
        }
        return new HttpResponseTo(method);
    } catch (final Throwable e) {
        if (log.isInfoEnabled()) {
            log.info("Failed to receive HTTP request from " + url + ": " + e.getMessage());
        }
    }
    return null;
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * ?log.//from   w  w  w .j  a va2  s.c  o  m
 *
 * @param httpMethod
 *            the http method
 * @param httpClientConfig
 *            the http client config
 * @return the http method response attribute map for log
 */
private static Map<String, Object> getHttpMethodResponseAttributeMapForLog(HttpMethod httpMethod,
        HttpClientConfig httpClientConfig) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();

    Object statusCode = null;
    try {
        statusCode = httpMethod.getStatusCode();
    } catch (Exception e) {
        statusCode = e.getClass().getName() + " " + e.getMessage();
    }

    String statusText = null;
    try {
        statusText = httpMethod.getStatusText();
    } catch (Exception e) {
        statusText = e.getClass().getName() + " " + e.getMessage();
    }

    map.put("httpMethod.getRequestHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getRequestHeaders()));

    map.put("httpMethod.getStatusCode()", statusCode);
    map.put("httpMethod.getStatusText()", statusText);
    map.put("httpMethod.getStatusLine()", "" + httpMethod.getStatusLine());

    map.put("httpMethod.getResponseHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getResponseHeaders()));

    map.put("httpMethod.getResponseFooters()", httpMethod.getResponseFooters());
    map.put("httpClientConfig", httpClientConfig);

    return map;
}

From source file:com.zimbra.qa.unittest.TestWsdlServlet.java

String doWsdlServletRequest(String wsdlUrl, boolean admin, int expectedCode) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;//  w  w w. ja  v  a  2s  .  c o m
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);

    String url = protoHostPort + wsdlUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        ZimbraLog.test.debug("respCode=" + respCode);
        ZimbraLog.test.debug("statusCode=" + statusCode);
        ZimbraLog.test.debug("statusLine=" + statusLine);

        assertTrue("Response code", respCode == expectedCode);
        assertTrue("Status code", statusCode == expectedCode);

        Header[] respHeaders = method.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            String header = respHeaders[i].toString();
            ZimbraLog.test.debug("ResponseHeader:" + header);
        }

        String respBody = method.getResponseBodyAsString();
        // ZimbraLog.test.debug("Response Body:" + respBody);
        return respBody;

    } catch (HttpException e) {
        fail("Unexpected HttpException" + e);
        throw e;
    } catch (IOException e) {
        fail("Unexpected IOException" + e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.twinsoft.convertigo.engine.PacManager.java

private String downloadPacContent(String url) throws IOException {
    if (url == null) {
        Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null");
        throw new IOException("Invalid PAC script URL: null");
    }//from   w  w  w.j  a va  2 s  .c  om

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("(PacManager) Method failed: " + method.getStatusLine());
    }

    return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

private int executeMethod(HttpMethod method, Host host) throws HTTPErrorException {
    try {// w ww  . j  av a 2  s . c  om
        int httpStatus = getClient(host).executeMethod(method);
        if (httpStatus != HttpStatus.SC_OK)
            getLog().error("Method failed: " + method.getStatusLine());
        return httpStatus;
    } catch (Exception e) {
        getLog().error(
                "Could not force a build on project, either the webpage is not available, or there was a timeout in connecting to the cruise server.",
                e);
        throw new HTTPErrorException(
                "Could not force a build on project, either the webpage is not available, or there was a timeout in connecting to the cruise server.",
                e);
    }
}

From source file:com.uber.jenkins.phabricator.uberalls.UberallsClient.java

public String getCoverage(String sha) {
    URIBuilder builder;/*w ww .j  a v a 2s  .co  m*/
    try {
        builder = getBuilder().setParameter("sha", sha).setParameter("repository", repository);

        HttpClient client = getClient();
        HttpMethod request = new GetMethod(builder.build().toString());
        int statusCode = client.executeMethod(request);

        if (statusCode != HttpStatus.SC_OK) {
            logger.info(TAG, "Call failed: " + request.getStatusLine());
            return null;
        }
        return request.getResponseBodyAsString();
    } catch (HttpResponseException e) {
        if (e.getStatusCode() != 404) {
            e.printStackTrace(logger.getStream());
        }
    } catch (Exception e) {
        e.printStackTrace(logger.getStream());
    }
    return null;
}

From source file:mitm.common.security.ca.handlers.comodo.AutoAuthorize.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Authorize. Message: " + httpMethod.getStatusLine());
    }/*  w ww.  ja  va  2s.  c o  m*/

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    LineNumberReader lineReader = new LineNumberReader(new StringReader(response));

    String statusParameter = lineReader.readLine();

    errorCode = CustomClientStatusCode.fromCode(statusParameter);

    if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
        error = true;

        errorMessage = lineReader.readLine();
    } else {
        error = false;
    }
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

void copyProxyReponse(HttpMethod proxyResponse, HttpServletResponse response) throws IOException {
    copyProxyHeaders(proxyResponse.getResponseHeaders(), response);
    response.setContentLength(getResponseContentLength(proxyResponse));
    copy(proxyResponse.getResponseBodyAsStream(), response.getOutputStream());
    if (proxyResponse.getStatusLine() != null) {
        int statCode = proxyResponse.getStatusCode();
        response.setStatus(statCode);//w  w  w  .j  a va 2 s. co  m
    }
}

From source file:mitm.common.security.ca.handlers.comodo.ApplyCustomClientCert.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error applying for Custom Client Cert. Message: " + httpMethod.getStatusLine());
    }/*w w w. j a va2 s  .c om*/

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    Map<String, String[]> parameters = NetUtils.parseQuery(response);

    String errorCodeParam = getValue(parameters, "errorCode");

    if (!StringUtils.isEmpty(errorCodeParam)) {
        errorCode = CustomClientStatusCode.fromCode(errorCodeParam);

        error = true;

        errorMessage = getValue(parameters, "errorMessage");
    } else {
        error = false;

        orderNumber = getValue(parameters, "orderNumber");
        collectionCode = getValue(parameters, "collectionCode");

        if (StringUtils.isEmpty(orderNumber)) {
            throw new IOException(new CustomClientCertException("orderNumber is missing."));
        }
    }
}

From source file:com.zimbra.qa.unittest.TestPreAuthServlet.java

void doPreAuthServletRequest(String preAuthUrl, boolean admin) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();

    String protoHostPort;//from ww w .j  a  va  2s  .  c  om
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);

    String url = protoHostPort + preAuthUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
        /*
        System.out.println("Headers");
        Header[] respHeaders = method.getResponseHeaders();
        for (int i=0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        System.out.println(header);
        }
                
        String respBody = method.getResponseBodyAsString();
        // System.out.println("respBody=" + respBody);
        */

    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
}