Example usage for org.apache.commons.httpclient HttpClient HttpClient

List of usage examples for org.apache.commons.httpclient HttpClient HttpClient

Introduction

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

Prototype

public HttpClient() 

Source Link

Usage

From source file:jp.go.nict.langrid.management.logic.service.HttpClientUtil.java

/**
 * /*  ww  w  .  j a  v a 2 s  .c  o m*/
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

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  .  j  a va2 s  .  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:idea.clientRequests.httpClientRequester.java

public boolean doHttpget(String csUrl) {
    boolean bStatus = false;
    m_responseBody = null;//from   w w  w. j ava2 s. c o m
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(csUrl);

    // Provide custom retry handler is necessary
    DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(3, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        // Read the response body.
        m_responseBody = method.getResponseBody();

        bStatus = true;
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return bStatus;
}

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 .  c  om*/
 * @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:es.carebear.rightmanagement.client.user.LogInUser.java

public LogInUser(String baseUri) {
    this.baseUri = baseUri;
    this.httpClient = new HttpClient();
}

From source file:es.carebear.rightmanagement.client.admin.CreateUser.java

public CreateUser(String baseUri) {
    this.baseUri = baseUri;
    this.httpClient = new HttpClient();
}

From source file:com.curl.orb.client.ORBSession.java

public ORBSession() {
    httpClient = new HttpClient();
}

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  w w . j av  a2  s. c  om
        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: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  www .  j  a va2s .  c om
        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:com.legendshop.central.license.HttpClientLicenseHelper.java

public String postMethod(String paramString) {
    String str = null;//from  ww w .  j a  v  a  2 s  .  c  o m
    HttpClient localHttpClient = new HttpClient();
    PostMethod localPostMethod = new PostMethod(this._$1);
    NameValuePair[] arrayOfNameValuePair = new NameValuePair[1];
    arrayOfNameValuePair[0] = new NameValuePair("_ENTITY", paramString);
    localPostMethod.addParameters(arrayOfNameValuePair);
    try {
        localHttpClient.executeMethod(localPostMethod);
        str = localPostMethod.getResponseBodyAsString();
    } catch (Exception localException) {
    } finally {
        localPostMethod.releaseConnection();
    }
    return str;
}