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.edge.media.service.util.HttpUtil.java

public void verifyUrl(String url, String path, String suffix) throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod method = new HeadMethod(url + path + suffix);
    int statusCode = 0;
    try {//from   w ww .jav a  2s . c  o  m
        statusCode = client.executeMethod(method);
    } catch (IOException e) {
        // do nothing
    }
    method.releaseConnection();

    if (statusCode != HttpStatus.SC_OK) {
        StringBuilder err = new StringBuilder("Stream does not exist: ");
        err.append(path);
        err.append(", ");
        err.append(statusCode);
        throw new Exception(err.toString());
    }
}

From source file:fr.matriciel.AnnotationClient.java

public static String request(HttpMethod method) throws AnnotationException {

    String response = null;//from  w ww. j  a  v a 2s. c o m

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        //TODO Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        response = new String(responseBody);

    } catch (HttpException e) {
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.utest.domain.service.util.FileUploadUtil.java

public static void uploadFile(final File targetFile, final String targetURL, final String targerFormFieldName_)
        throws Exception {
    final PostMethod filePost = new PostMethod(targetURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    filePost.addRequestHeader("X-Atlassian-Token", "no-check");
    try {/*from   w  w  w .j a  v a  2  s .  com*/
        final FilePart fp = new FilePart(targerFormFieldName_, targetFile);
        fp.setTransferEncoding(null);
        final Part[] parts = { fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        final HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        final int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            Logger.getLogger(FileUploadUtil.class)
                    .info("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (final Exception ex) {
        Logger.getLogger(FileUploadUtil.class)
                .error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage(), ex);
        throw ex;
    } finally {
        Logger.getLogger(FileUploadUtil.class).debug(new String(filePost.getResponseBody()));
        filePost.releaseConnection();
    }

}

From source file:apm.common.utils.HttpTookit.java

/**
 * HTTP GET?HTML// w w w .  java  2 s  .  c  om
 * 
 * @param url
 *            URL?
 * @param queryString
 *            ?,?null
 * @param charset
 *            
 * @param pretty
 *            ?
 * @return ?HTML
 */
public static String doGet(String url, String queryString, String charset, boolean pretty) {
    StringBuffer response = new StringBuffer();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        if (StringUtils.isNotBlank(queryString))
            // get??http?????%?
            method.setQueryString(URIUtil.encodeQuery(queryString));
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), charset));
            String line;
            while ((line = reader.readLine()) != null) {
                if (pretty) {
                    response.append(line).append(System.getProperty("line.separator"));
                } else {
                    response.append(line);
                }
            }
            reader.close();
        }
    } catch (URIException e) {
        log.error("HTTP Get?" + queryString + "???", e);
    } catch (IOException e) {
        log.error("HTTP Get" + url + "??", e);
    } finally {
        method.releaseConnection();
    }
    return response.toString();
}

From source file:com.tc.admin.UpdateCheckRequestTest.java

public static String getResponseBody(URL url, HttpClient client) throws ConnectException, IOException {
    GetMethod get = new GetMethod(url.toString());

    get.setFollowRedirects(true);// www.  j  a va  2  s  . c om
    try {
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            throw new ConnectException(
                    "The http client has encountered a status code other than ok for the url: " + url
                            + " status: " + HttpStatus.getStatusText(status));
        }
        return get.getResponseBodyAsString();
    } finally {
        get.releaseConnection();
    }
}

From source file:it.geosolutions.geonetwork.op.GNInfo.java

public static boolean ping(HTTPUtils connection, String serviceURL) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("PING");

    connection.setIgnoreResponseContentOnSuccess(true);
    String url = serviceURL + "/srv/eng/util.ping";

    try {//  w ww.  ja v  a 2 s. c o  m
        connection.get(url);
    } catch (MalformedURLException ex) {
        LOGGER.error(ex.getMessage());
        return false;
    }

    if (connection.getLastHttpStatus() != HttpStatus.SC_OK) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("PING failed");
        return false;
    }

    return true;
}

From source file:fr.jayasoft.ivy.url.BasicURLHandler.java

public boolean isReachable(URL url, int timeout) {
    try {//w w w. j av a2  s. c  o m
        URLConnection con = url.openConnection();
        if (con instanceof HttpURLConnection) {
            int status = ((HttpURLConnection) con).getResponseCode();
            if (status == HttpStatus.SC_OK) {
                return true;
            }
            if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                Message.warn("Your proxy requires authentication.");
            } else if (String.valueOf(status).startsWith("4")) {
                Message.verbose(
                        "CLIENT ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            } else if (String.valueOf(status).startsWith("5")) {
                Message.error(
                        "SERVER ERROR: " + ((HttpURLConnection) con).getResponseMessage() + " url=" + url);
            }
            Message.debug("HTTP response status: " + status + " url=" + url);
        } else {
            int contentLength = con.getContentLength();
            return contentLength > 0;
        }
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info(
                "You probably access the destination server through a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("Server access Error: " + e.getMessage() + " url=" + url);
    }
    return false;
}

From source file:alluxio.util.network.HttpUtils.java

/**
 * Uses the post method to send a url with arguments by http, this method can call RESTful Api.
 *
 * @param url the http url/*  w  w  w .  j a  v  a  2 s.com*/
 * @param timeout milliseconds to wait for the server to respond before giving up
 * @param processInputStream the response body stream processor
 */
public static void post(String url, Integer timeout, IProcessInputStream processInputStream)
        throws IOException {
    Preconditions.checkNotNull(timeout, "timeout");
    Preconditions.checkNotNull(processInputStream, "processInputStream");
    PostMethod postMethod = new PostMethod(url);
    try {
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream inputStream = postMethod.getResponseBodyAsStream();
            processInputStream.process(inputStream);
        } else {
            throw new IOException("Failed to perform POST request. Status code: " + statusCode);
        }
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:io.aos.protocol.http.commons.CommonsHttpClient.java

public static void get(String url) {

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {/*from  w  ww  .ja v a2s. co m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        LOG.debug(new String(responseBody, "UTF-8"));
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

}

From source file:es.carebear.rightmanagement.client.group.AddUserToGroup.java

public void AddUser(String executing, String target, String group)
        throws BadRequestException, InternalServerErrorException, IOException, UnknownResponseException {
    PostMethod postMethod = new PostMethod(baseUri + "/client/groups/add/" + target + "/" + group);
    postMethod.addParameter("authName", executing);
    int responseCode = httpClient.executeMethod(postMethod);

    switch (responseCode) {
    case HttpStatus.SC_OK:
        break;/*w ww .  j  av a2  s  .co m*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new BadRequestException();
    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
        throw new InternalServerErrorException();
    case HttpStatus.SC_FORBIDDEN:
        throw new ForbiddenException();
    default:
        throw new UnknownResponseException((new Integer(responseCode)).toString());
    }
}