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:httpclient.conn.OperatorConnectProxy.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", 8666, "http");

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

    // 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);
    // In a real application, request interceptors should be used
    // to add the required headers.
    req.addHeader("Host", target.getHostName());

    HttpContext ctx = new BasicHttpContext();

    OperatedClientConnection conn = scop.createConnection();
    try {/*from w w w. j  a  v a 2 s. c  o  m*/
        System.out.println("opening connection to " + proxy);
        scop.openConnection(conn, proxy, null, ctx, params);

        // Creates a request to tunnel a connection.
        // For details see RFC 2817, section 5.2
        String authority = target.getHostName() + ":" + target.getPort();
        HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
        // In a real application, request interceptors should be used
        // to add the required headers.
        connect.addHeader("Host", authority);

        System.out.println("opening tunnel to " + target);
        conn.sendRequestHeader(connect);
        // there is no request entity
        conn.flush();

        System.out.println("receiving confirmation for tunnel");
        HttpResponse connected = conn.receiveResponseHeader();
        System.out.println("----------------------------------------");
        printResponseHeader(connected);
        System.out.println("----------------------------------------");
        int status = connected.getStatusLine().getStatusCode();
        if ((status < 200) || (status > 299)) {
            System.out.println("unexpected status code " + status);
            System.exit(1);
        }
        System.out.println("receiving response body (ignored)");
        conn.receiveResponseEntity(connected);

        // Now we have a tunnel to the target. As we will be creating a
        // layered TLS/SSL socket immediately afterwards, updating the
        // connection with the new target is optional - but good style.
        // The scheme part of the target is already "https", though the
        // connection is not yet switched to the TLS/SSL protocol.
        conn.update(null, target, false, params);

        System.out.println("layering secure connection");
        scop.updateSecureConnection(conn, target, ctx, params);

        // finally we have the secure connection and can send the request

        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("----------------------------------------");
        printResponseHeader(rsp);
        System.out.println("----------------------------------------");

    } finally {
        System.out.println("closing connection");
        conn.close();
    }
}

From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java

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

    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
    //CountDownLatch requestCount = new CountDownLatch(3);
    CountDownLatch requestCount = new CountDownLatch(1);

    BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(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());
            }//from  www.ja v  a2 s. c  o m
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[1];
    reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null,
            new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount));
    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

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

    ioReactor.shutdown();

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

From source file:NHttpClient.java

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

    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
    CountDownLatch requestCount = new CountDownLatch(3);

    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());
            }/* w ww .  j  a v  a 2 s  .  c  o  m*/
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[3];
    reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"),
            new MySessionRequestCallback(requestCount));
    reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null,
            new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount));
    reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null,
            new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount));

    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

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

    ioReactor.shutdown();

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

From source file:pt.ua.tm.neji.web.test.TestREST.java

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);/*from ww w.  j  av  a2  s  .  c  o m*/

    MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sf, 8010));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    String url = "https://localhost:8010/annotate/default/export?tool=becas-webapp&email=bioinformatics@ua.pt";

    // POST
    CloseableHttpClient client = new DefaultHttpClient(ccm, params);

    HttpPost post = new HttpPost(url);
    //post.setHeader("Content-Type", "application/json");

    List<NameValuePair> keyValuesPairs = new ArrayList();
    //keyValuesPairs.add(new BasicNameValuePair("format", "neji"));
    keyValuesPairs.add(new BasicNameValuePair("fromFile", "false"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true,\"ANAT\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"DISO\":true}"));
    //keyValuesPairs.add(new BasicNameValuePair("groups", "{\"ANAT\":true}"));
    keyValuesPairs.add(new BasicNameValuePair("text", text));
    keyValuesPairs.add(new BasicNameValuePair("crlf", "false"));
    post.setEntity(new UrlEncodedFormEntity(keyValuesPairs));

    HttpResponse response = client.execute(post);

    String result = IOUtils.toString(response.getEntity().getContent());

    System.out.println(result);
}

From source file:Main.java

private static String reverseGeocode(String url) {
    try {//from  w w w.  j  a v  a  2s. c  o  m
        HttpGet httpGet = new HttpGet(url);
        BasicHttpParams httpParams = new BasicHttpParams();
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
        HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == HttpStatus.SC_OK) {
            String charSet = EntityUtils.getContentCharSet(httpResponse.getEntity());
            if (null == charSet) {
                charSet = "UTF-8";
            }
            String str = new String(EntityUtils.toByteArray(httpResponse.getEntity()), charSet);
            defaultHttpClient.getConnectionManager().shutdown();
            return str;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String reverseGeocode(String url) {
    try {/*from w  ww . j  a v  a  2s . c  om*/
        HttpGet httpGet = new HttpGet(url);
        BasicHttpParams httpParams = new BasicHttpParams();
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
        HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == HttpStatus.SC_OK) {
            String charSet = EntityUtils.getContentCharSet(httpResponse.getEntity());
            if (null == charSet) {
                charSet = "UTF-8";
            }
            String str = new String(EntityUtils.toByteArray(httpResponse.getEntity()), charSet);
            defaultHttpClient.getConnectionManager().shutdown();
            Log.i("-----------", "str = " + str);
            return str;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String getHttpClientString(String path) {
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParams);
    DefaultHttpClient httpClient = (DefaultHttpClient) client;
    HttpResponse httpResponse = null;//from w  w  w  .j  av a  2 s  .  c o  m
    String result = "";
    try {
        httpResponse = httpClient.execute(new HttpGet(path));
        int res = httpResponse.getStatusLine().getStatusCode();
        if (res == 200) {
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line.trim());
            }
            reader.close();
            in.close();
            result = sb.toString();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

From source file:Main.java

private static void ensureHttpClient() {
    if (httpClient != null)
        return;//from   w w w. ja  va2 s  .c  o  m

    BasicHttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 45000);
    HttpConnectionParams.setSoTimeout(params, 30000);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    try {
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } catch (Exception e) {
        Log.w(TAG, "Unable to register HTTPS socket factory: " + e.getLocalizedMessage());
    }

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, registry);
    httpClient = new DefaultHttpClient(connManager, params);
}

From source file:Main.java

public static HttpClient getHttpClient() {

    if (httpClient != null) {
        return httpClient;
    }// w w  w  .  j  a v a2 s.  co m

    synchronized (HTTP_CLIENT) {
        HttpParams defaultParams = new BasicHttpParams();
        defaultParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
        defaultParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
        defaultParams.setLongParameter(ConnManagerPNames.TIMEOUT, 6000);

        SchemeRegistry scheme = new SchemeRegistry();
        scheme.register(new Scheme("http", new PlainSocketFactory(), 80));
        scheme.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager connMgr = new ThreadSafeClientConnManager(defaultParams, scheme);

        httpClient = new DefaultHttpClient(connMgr, defaultParams);
    }

    return httpClient;
}

From source file:Main.java

public static String getResultPost(String uri, List<NameValuePair> params) {
    String Result = null;//from www  . j a va2 s  .c om
    try {
        if (uri == null) {
            return "";
        }
        HttpPost httpRequest = new HttpPost(uri);
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        int res = httpResponse.getStatusLine().getStatusCode();
        if (res == 200) {

            StringBuilder builder = new StringBuilder();
            BufferedReader bufferedReader2 = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine()) {
                builder.append(s);
            }
            Result = builder.toString();

        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
        return "";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Result;
}