Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.gargoylesoftware.htmlunit.util.WebConnectionWrapperTest.java

/**
 * @throws Exception if the test fails// w  ww  . j  av  a  2  s  .co m
 */
@Test
public void wrapper() throws Exception {
    final List<NameValuePair> emptyList = Collections.emptyList();
    final WebResponseData data = new WebResponseData(new byte[] {}, HttpStatus.SC_OK, "", emptyList);
    final WebResponse response = new WebResponseImpl(data, URL_FIRST, HttpMethod.GET, 0);
    final WebRequestSettings wrs = new WebRequestSettings(URL_FIRST);

    final WebConnection realConnection = new WebConnection() {
        public WebResponse getResponse(final WebRequestSettings settings) {
            assertSame(wrs, settings);
            return response;
        }
    };

    final WebConnectionWrapper wrapper = new WebConnectionWrapper(realConnection);
    assertSame(response, wrapper.getResponse(wrs));
}

From source file:com.ironiacorp.http.impl.httpclient3.GetRequest.java

public HttpJob call() {
    URI uri = job.getUri();// w  w w .  ja  v  a 2s .co  m
    GetMethod getMethod = new GetMethod(uri.toString());
    HttpMethodResult result = new HttpMethodResult();

    try {
        int statusCode = client.executeMethod(getMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + getMethod.getStatusLine());
        }

        InputStream inputStream = getMethod.getResponseBodyAsStream();
        if (inputStream != null) {
            result.setContent(inputStream);
            result.setStatusCode(statusCode);
            job.setResult(result);
        }
    } catch (HttpException e) {
    } catch (IOException e) {
        // In case of an IOException the connection will be released
        // back to the connection manager automatically
    } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        getMethod.abort();
    }

    return job;
}

From source file:com.thoughtworks.go.agent.launcher.ServerCall.java

public static ServerResponseWrapper invoke(HttpMethod method) throws Exception {
    HashMap<String, String> headers = new HashMap<String, String>();
    HttpClient httpClient = new HttpClient();
    httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS);
    try {//from w w  w .java2s.c o  m
        final int status = httpClient.executeMethod(method);
        if (status == HttpStatus.SC_NOT_FOUND) {
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            out.println("Return Code: " + status);
            out.println("Few Possible Causes: ");
            out.println("1. Your Go Server is down or not accessible.");
            out.println(
                    "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent.");
            out.close();
            throw new Exception(sw.toString());
        }
        if (status != HttpStatus.SC_OK) {
            throw new Exception("Got status " + status + " " + method.getStatusText() + " from server");
        }
        for (Header header : method.getResponseHeaders()) {
            headers.put(header.getName(), header.getValue());
        }
        return new ServerResponseWrapper(headers, method.getResponseBodyAsStream());
    } catch (Exception e) {
        String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString();
        LOG.error(message);
        throw new Exception(message, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3Util.java

/**
 * ?url?ResponseBody,method=get/*ww w.ja  v  a2  s .co  m*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:es.carebear.rightmanagement.client.user.AddAllowedUserId.java

public void AddUser(String authName, String target, String rightMask) throws BadRequestException,
        InternalServerErrorException, IOException, UnknownResponseException, UnauthorizedException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/users/change/allowed");
    postMethod.addParameter("authName", authName);
    postMethod.addParameter("target", target);
    postMethod.addParameter("rightMask", rightMask);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;/*w  w w  .j a  v  a 2 s. c  om*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_UNAUTHORIZED:
        throw new UnauthorizedException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}

From source file:name.chengchao.myhttpclient.version3_1.HttpClient3UtilError.java

/**
 * ?url?ResponseBody,method=get/*from ww  w .ja  va  2 s . com*/
 * 
 * @param url exp:http://192.168.1.1:8080/dir/target.html
 * @return byte[]?
 */
public static byte[] getDataFromUrl(String url, int timeout) {
    if (StringUtils.isBlank(url)) {
        logger.error("url is blank!");
        return null;
    }
    HttpClient httpClient = new HttpClient();
    // 
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000);
    // ?
    httpClient.getParams().setSoTimeout(timeout);
    GetMethod method = new GetMethod(url);

    // fix???
    // method.setRequestHeader("Connection", "close");
    // ??1
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return method.getResponseBody();
        } else {
            throw new RuntimeException("http request error,return code:" + statusCode + ",msg:"
                    + new String(method.getResponseBody()));
        }
    } catch (HttpException e) {
        method.abort();
        logger.error(e.getMessage());
    } catch (IOException e) {
        method.abort();
        logger.error(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:net.sf.sail.webapp.domain.webservice.http.HttpGetRequestTest.java

protected void setUp() throws Exception {
    super.setUp();
    method = EasyMock.createMock(HttpMethod.class);
    request = new HttpGetRequest(AbstractHttpRestCommand.REQUEST_HEADERS_ACCEPT,
            AbstractHttpRestCommand.EMPTY_STRING_MAP, URL, HttpStatus.SC_OK);
}

From source file:it.pronetics.madstore.crawler.downloader.impl.DownloaderImpl.java

public Page download(Link link) {
    String url = link.getLink();/*from  ww  w  . j av a  2 s .  c o  m*/
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    try {
        LOG.info("Downloading page from: {}", url);
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            String data = method.getResponseBodyAsString();
            return new Page(link, data);
        } else {
            return new Page(link);
        }
    } catch (Exception e) {
        LOG.warn("Download failed: {}", url);
        LOG.warn(e.getMessage());
        LOG.debug(e.getMessage(), e);
        return new Page(link);
    } finally {
        method.releaseConnection();
    }
}

From source file:atg.taglib.json.JsonTestRunner.java

public void runTest() throws Exception {
    try {/*from  ww w . jav  a 2 s  . c o  m*/
        String msg;

        msg = MessageFormat.format("Running test {0}/{1}... ", testType, testNum);
        System.out.println(msg);

        ResponseData data = Helper.getData(testType, testNum);

        msg = MessageFormat.format("{0}/{1} - Status {2} is expected.", testType, testNum,
                data.expectedStatusCode);

        assertEquals(msg, data.expectedStatusCode, data.statusCode);

        if (data.statusCode == HttpStatus.SC_OK) {
            // Compare JSON objects
            msg = MessageFormat.format("{0}/{1} - JSON Objects should match.", testType, testNum);
            System.out.print(msg);
            assertEquals(msg, data.expectedJson, data.json);
        } else {
            String expectedMsg = Messages.getString(data.expectedMsgKey);
            // If the expected Msg has a substitued value, just check the returned string
            // up to that point - we can't know what value will ctually be substituted
            if (expectedMsg.contains("{0}")) {
                expectedMsg = expectedMsg.substring(0, expectedMsg.indexOf("{0}"));
            }
            msg = MessageFormat.format("{0}/{1} - Exception should contain key {2} - \"{3}\"", testType,
                    testNum, data.expectedMsgKey, expectedMsg);
            System.out.print(msg);
            assertTrue(msg, data.body.contains(expectedMsg));
        }
        System.out.println(" OK");
    } catch (Exception e) {
        String msg = MessageFormat.format("{0}/{1} - Exception occurred during test.", testType, testNum);
        System.out.println(msg);
        System.out.println(e);
        e.printStackTrace(System.out);
        throw new Exception(msg, e);
    }
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

public static String getResponseBodyAsString(HttpMethod method, Integer tryTimes, String responseCharSet,
        Integer maximumResponseByteSize, Integer soTimeoutMill) {
    init();/*from www .  j  av  a 2  s  .com*/
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (StringUtils.isBlank(responseCharSet)) {
        responseCharSet = "utf-8";
    }
    if (maximumResponseByteSize == null) {
        maximumResponseByteSize = 50 * 1024 * 1024;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    InputStream httpInputStream = null;
    for (int i = 0; i < tryTimes; i++) {
        try {
            int responseCode = client.executeMethod(method);
            if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                if (method instanceof HttpMethodBase) {
                    responseCharSet = ((HttpMethodBase) method).getResponseCharSet();
                }
                int read = 0;
                byte[] cbuf = new byte[4096];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                httpInputStream = method.getResponseBodyAsStream();
                while ((read = httpInputStream.read(cbuf)) >= 0) {
                    baos.write(cbuf, 0, read);
                    if (baos.size() >= maximumResponseByteSize) {
                        break;
                    }
                }
                String content = baos.toString(responseCharSet);
                return content;
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
            return "";
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            IOUtils.closeQuietly(httpInputStream);
            method.releaseConnection();
        }
    }
    return "";
}