Example usage for org.apache.http.params BasicHttpParams BasicHttpParams

List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams

Introduction

In this page you can find the example usage for org.apache.http.params BasicHttpParams BasicHttpParams.

Prototype

public BasicHttpParams() 

Source Link

Usage

From source file:App.App.java

public static void main(String[] args) throws IOException {
    File inFile = new File("C:\\Data\\LogTest.java");
    FileInputStream fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://localhost:8080/rest_j2ee/rest/files/upload");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);/*from w  ww  .j  a va2 s.c  o  m*/
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println("[" + statusCode + "] " + responseString);
}

From source file:httpclient.client.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(params, Constants.BROWSER_TYPE);
    HttpProtocolParams.setUseExpectContinue(params, true);
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    String loginURL = "http://10.1.1.251/login.asp";
    HttpGet httpget = new HttpGet(loginURL);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity.consumeContent();//from  w w w.ja v  a2 s  .c  o  m
    }
    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    HttpPost httpost = new HttpPost(loginURL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("name", "fangdj"));
    nvps.add(new BasicNameValuePair("passwd", "1111"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);
    entity = response.getEntity();
    for (Header h : response.getAllHeaders()) {
        System.out.println(h);
    }
    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();
    }

    System.out.println("Post logon cookies:");
    cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    String mainURL = "http://10.1.1.251/ONWork/Record_save.asp";

    HttpPost mainHttPost = new HttpPost(mainURL);
    List<NameValuePair> mainNvps = new ArrayList<NameValuePair>();
    mainNvps.add(new BasicNameValuePair("EMP_NO", "13028"));
    mainNvps.add(new BasicNameValuePair("pwd", "1111"));
    mainNvps.add(new BasicNameValuePair("cmd2", "Apply"));

    httpost.setEntity(new UrlEncodedFormEntity(mainNvps, HTTP.UTF_8));

    response = httpclient.execute(mainHttPost);
    System.out.println(Tools.InputStreamToString(response.getEntity().getContent()));
    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:httpclient.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpclient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/",
            "http://jakarta.apache.org/commons/httpclient/",
            "http://svn.apache.org/viewvc/jakarta/httpcomponents/" };

    IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
    connEvictor.start();//from  w ww. j  a  v  a 2  s.c o  m

    for (int i = 0; i < urisToGet.length; i++) {
        String requestURI = urisToGet[i];
        HttpGet req = new HttpGet(requestURI);

        System.out.println("executing request " + requestURI);

        HttpResponse rsp = httpclient.execute(req);
        HttpEntity entity = rsp.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");

        if (entity != null) {
            entity.consumeContent();
        }
    }

    // Sleep 10 sec and let the connection evictor do its job
    Thread.sleep(20000);

    // Shut down the evictor thread
    connEvictor.shutdown();
    connEvictor.join();

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.hilatest.httpclient.apacheexample.ClientMultiThreadedExecution.java

public static void main(String[] args) throws Exception {
    // Create and initialize HTTP parameters
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    // Create and initialize scheme registry 
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(cm, params);

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core/",
            "http://hc.apache.org/httpcomponents-client/", "http://svn.apache.org/viewvc/httpcomponents/" };

    // create a thread for each URI
    GetThread[] threads = new GetThread[urisToGet.length];
    for (int i = 0; i < threads.length; i++) {
        HttpGet httpget = new HttpGet(urisToGet[i]);
        threads[i] = new GetThread(httpClient, httpget, i + 1);
    }//from  www.j a  va  2s  .  c  o  m

    // start the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].start();
    }

    // join the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].join();
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpClient.getConnectionManager().shutdown();
}

From source file:httpclient.client.ClientExecuteDirect.java

public static void main(String[] args) throws Exception {

    HttpHost target = new HttpHost("www.baidu.com", 80, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(connMgr, params);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target);

    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers = rsp.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i]);
    }/*from w ww.  j  a va  2 s  .co  m*/
    System.out.println("----------------------------------------");

    if (entity != null) {
        System.out.println(EntityUtils.toString(entity));
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.hilatest.httpclient.apacheexample.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("issues.apache.org", 443, "https");
    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + proxy);
    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers = rsp.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i]);
    }/*from   ww w  .j  ava  2  s.c o m*/
    System.out.println("----------------------------------------");

    if (entity != null) {
        System.out.println(EntityUtils.toString(entity));
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:httpclient.client.ClientExecuteProxy.java

public static void main(String[] args) throws Exception {

    // make sure to use a proxy that supports CONNECT
    HttpHost target = new HttpHost("vote.sun0769.com/include/code.asp?s=youthnet&aj=0.70161835174741", 80,
            "http");
    HttpHost proxy = new HttpHost("59.36.98.154", 80, "http");

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "GB2312");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpGet req = new HttpGet("/");

    System.out.println("executing request to " + target + " via " + proxy);
    HttpResponse rsp = httpclient.execute(target, req);
    HttpEntity entity = rsp.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(rsp.getStatusLine());
    Header[] headers = rsp.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i]);
    }//from w w w  .ja  va2s  .co m
    System.out.println("----------------------------------------");

    if (entity != null) {
        System.out.println(EntityUtils.toString(entity));
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:httpclient.conn.OperatorConnectDirect.java

public static void main(String[] args) throws Exception {
    HttpHost target = new HttpHost("jakarta.apache.org", 80, "http");

    // some general setup
    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));

    // Prepare parameters.
    // Since this example doesn't use the full core framework,
    // only few parameters are actually required.
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    // one operator can be used for many connections
    ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);

    HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
    req.addHeader("Host", target.getHostName());

    HttpContext ctx = new BasicHttpContext();

    OperatedClientConnection conn = scop.createConnection();
    try {//from ww  w. ja v  a2 s  .c  o m
        System.out.println("opening connection to " + target);
        scop.openConnection(conn, target, null, ctx, params);
        System.out.println("sending request");
        conn.sendRequestHeader(req);
        // there is no request entity
        conn.flush();

        System.out.println("receiving response header");
        HttpResponse rsp = conn.receiveResponseHeader();

        System.out.println("----------------------------------------");
        System.out.println(rsp.getStatusLine());
        Header[] headers = rsp.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
    } finally {
        System.out.println("closing connection");
        conn.close();
    }
}

From source file:org.apache.droids.examples.cli.SimpleRuntime.java

public static void main(String[] args) throws Exception {

    if (args.length < 1) {
        System.out.println("Please specify a URL to crawl");
        System.exit(-1);//from  w ww .  j ava2  s .  c om
    }
    String targetURL = args[0];

    // Create parser factory. Support basic HTML markup only
    ParserFactory parserFactory = new ParserFactory();
    TikaDocumentParser tikaParser = new TikaDocumentParser();
    parserFactory.getMap().put("text/html", tikaParser);

    // Create protocol factory. Support HTTP/S only.
    ProtocolFactory protocolFactory = new ProtocolFactory();

    // Create and configure HTTP client
    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean hppb = new HttpProtocolParamBean(params);
    HttpConnectionParamBean hcpb = new HttpConnectionParamBean(params);
    ConnManagerParamBean cmpb = new ConnManagerParamBean(params);

    // Set protocol parametes
    hppb.setVersion(HttpVersion.HTTP_1_1);
    hppb.setContentCharset(HTTP.ISO_8859_1);
    hppb.setUseExpectContinue(true);
    // Set connection parameters
    hcpb.setStaleCheckingEnabled(false);
    // Set connection manager parameters
    ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean();
    connPerRouteBean.setDefaultMaxPerRoute(2);
    cmpb.setConnectionsPerRoute(connPerRouteBean);

    DroidsHttpClient httpclient = new DroidsHttpClient(params);

    HttpProtocol httpProtocol = new HttpProtocol(httpclient);
    protocolFactory.getMap().put("http", httpProtocol);
    protocolFactory.getMap().put("https", httpProtocol);

    // Create URL filter factory.
    URLFiltersFactory filtersFactory = new URLFiltersFactory();
    RegexURLFilter defaultURLFilter = new RegexURLFilter();
    defaultURLFilter.setFile("classpath:/regex-urlfilter.txt");
    filtersFactory.getMap().put("default", defaultURLFilter);

    // Create handler factory. Provide sysout handler only.
    HandlerFactory handlerFactory = new HandlerFactory();
    SysoutHandler defaultHandler = new SysoutHandler();
    handlerFactory.getMap().put("default", defaultHandler);

    // Create droid factory. Leave it empty for now.
    DroidFactory<Link> droidFactory = new DroidFactory<Link>();

    // Create default droid
    SimpleDelayTimer simpleDelayTimer = new SimpleDelayTimer();
    simpleDelayTimer.setDelayMillis(100);

    Queue<Link> simpleQueue = new LinkedList<Link>();

    SequentialTaskMaster<Link> taskMaster = new SequentialTaskMaster<Link>();
    taskMaster.setDelayTimer(simpleDelayTimer);
    taskMaster.setExceptionHandler(new DefaultTaskExceptionHandler());

    CrawlingDroid helloCrawler = new SysoutCrawlingDroid(simpleQueue, taskMaster);
    helloCrawler.setFiltersFactory(filtersFactory);
    helloCrawler.setParserFactory(parserFactory);
    helloCrawler.setProtocolFactory(protocolFactory);

    Collection<String> initialLocations = new ArrayList<String>();
    initialLocations.add(targetURL);
    helloCrawler.setInitialLocations(initialLocations);

    // Initialize and start the crawler
    helloCrawler.init();
    helloCrawler.start();

    // Await termination
    helloCrawler.getTaskMaster().awaitTermination(0, TimeUnit.MILLISECONDS);
    // Shut down the HTTP connection manager
    httpclient.getConnectionManager().shutdown();
}

From source file:wh.contrib.RewardOptimizerHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT,
                    "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    RequestCount requestCount = new RequestCount(1);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//ww  w  .  ja  v  a  2 s  .com
            System.out.println("Shutdown");
        }

    });
    t.start();

    List<SessionRequest> reqs = new ArrayList<SessionRequest>();
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.yahoo.com", 80), 
    //                null, 
    //                new HttpHost("www.yahoo.com"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.google.com", 80), 
    //                null,
    //                new HttpHost("www.google.ch"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.apache.org", 80), 
    //                null,
    //                new HttpHost("www.apache.org"),
    //                null));

    reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null,
            new HttpHost("www.wowhead.com"), null));

    // Block until all connections signal
    // completion of the request execution
    synchronized (requestCount) {
        while (requestCount.getValue() > 0) {
            requestCount.wait();
        }
    }

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}