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

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

Introduction

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

Prototype

public HttpConnectionManager getHttpConnectionManager()

Source Link

Usage

From source file:com.blueferdi.diamondbox.jetty.connector.HttpClientDemo.java

public static void main(String[] args) throws IOException {
    HttpClient client = new HttpClient();

    client.getHttpConnectionManager().getParams().setSoTimeout(1);

    int i = 1000;

    while (i > 0) {
        try {// w  w w  . j  a v  a  2s.c  o m
            GetMethod method = new GetMethod("http://localhost:8080/testblocking/BlockingServlet");
            method.setRequestHeader("Connection", "close");
            client.executeMethod(method);
        } catch (Exception ex) {
            i--;
            System.out.println(i);
        }
    }
}

From source file:CookieDemoApp.java

/**
 *
 * Usage:/*w  w w  .  ja v  a2  s  .c om*/
 *          java CookieDemoApp http://mywebserver:80/
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage: java CookieDemoApp <url>");
        System.err.println("<url> The url of a webpage");
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    System.out.println("Target URL: " + strURL);

    // Get initial state object
    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and 
    // re-created, using a persistence mechanism of choice,
    Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);
    // and then added to your HTTP state instance
    initialState.addCookie(mycookie);

    // Get HTTP client instance
    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    httpclient.setState(initialState);

    // RFC 2101 cookie management spec is used per default
    // to parse, validate, format & match cookies
    httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    // A different cookie management spec can be selected
    // when desired

    //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE);
    // Netscape Cookie Draft spec is provided for completeness
    // You would hardly want to use this spec in real life situations
    //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // Compatibility policy is provided in order to mimic cookie
    // management of popular web browsers that is in some areas 
    // not 100% standards compliant

    // Get HTTP GET method
    GetMethod httpget = new GetMethod(strURL);
    // Execute HTTP GET
    int result = httpclient.executeMethod(httpget);
    // Display status code
    System.out.println("Response status code: " + result);
    // Get all the cookies
    Cookie[] cookies = httpclient.getState().getCookies();
    // Display the cookies
    System.out.println("Present cookies: ");
    for (int i = 0; i < cookies.length; i++) {
        System.out.println(" - " + cookies[i].toExternalForm());
    }
    // Release current connection to the connection pool once you are done
    httpget.releaseConnection();
}

From source file:edu.caltech.ipac.firefly.server.util.multipart.MultiPartPostBuilder.java

public static void main(String[] args) {
    HttpClient client = new HttpClient();
    System.out.println("conn manager= " + client.getHttpConnectionManager().getClass().getName());
    System.out.println("def max per host= "
            + client.getHttpConnectionManager().getParams().getDefaultMaxConnectionsPerHost());
    System.out.println("total max = " + client.getHttpConnectionManager().getParams().getMaxTotalConnections());

}

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();//from   w w w.ja  va2 s .  c  o  m
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:com.zimbra.common.util.ZimbraHttpConnectionManager.java

public static void main(String[] args) {
    // dump httpclient package defaults
    System.out.println(dumpParams("httpclient package defaults", new HttpConnectionManagerParams(),
            new HttpClientParams()));

    System.out.println(dumpParams("Internal ZimbraHttpConnectionManager",
            ZimbraHttpConnectionManager.getInternalHttpConnMgr().getParams().getConnMgrParams(),
            ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient().getParams()));

    System.out.println(dumpParams("External ZimbraHttpConnectionManager",
            ZimbraHttpConnectionManager.getExternalHttpConnMgr().getParams().getConnMgrParams(),
            ZimbraHttpConnectionManager.getExternalHttpConnMgr().getDefaultHttpClient().getParams()));

    HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().getDefaultHttpClient();
    String connMgrName = httpClient.getHttpConnectionManager().getClass().getSimpleName();
    long connMgrTimeout = httpClient.getParams().getConnectionManagerTimeout();
    System.out.println("HttpConnectionManager for the HttpClient instance is: " + connMgrName);
    System.out.println("connection manager timeout for the HttpClient instance is: " + connMgrTimeout);
}

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  ww  w.j av a  2s  .  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:com.intellij.diagnostic.DevelopersLoader.java

public static Collection<Developer> fetchDevelopers(ProgressIndicator indicator) throws IOException {
    List<Developer> developers = new LinkedList<Developer>();
    developers.add(Developer.NULL);/*w w w.  ja  v a 2  s  . c o m*/

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT);
    HttpMethod method = new GetMethod(DEVELOPERS_LIST_URL);

    try {
        client.executeMethod(method);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(method.getResponseBodyAsStream(), DATA_CHARSET));

        try {
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                int i = line.indexOf('\t');
                if (i == -1)
                    throw new IOException("Protocol error");
                int id = Integer.parseInt(line.substring(0, i));
                String name = line.substring(i + 1);
                developers.add(new Developer(id, name));
                indicator.checkCanceled();
            }
            return developers;
        } finally {
            reader.close();
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.SmsUtil.java

/**
 * ??// w  w  w .  j av  a 2 s .c  om
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendSMS(String list, String subject, String content) {
    if ("false".equals(Constants.SENDSMS) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.SMS_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = subject;
        if (subject.getBytes().length > 150) {
            // ????content?subjectcontent??
            strContent = StringUtil.bSubstring(subject + ":" + content, 149);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK"))
                .replaceAll("#content#", URLEncoder.encode(strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("SmsUtil.sendWangWang statusCode:" + statusCode);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("SmsUtil.sendSMS", e);
    }
}

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/*ww  w.  jav  a  2s  .c o m*/
 * @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:name.chengchao.myhttpclient.version3_1.HttpClient3Util.java

/**
 * ?url?ResponseBody,method=get//from  ww  w  . ja va2  s. c o 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;
}