Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder build.

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug.
 *
 * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293,
 * which is related to http://sourceforge.net/p/htmlunit/bugs/535/
 *
 * @throws Exception if the test fails//from w ww  . j a v a2  s  .  c o m
 */
@Test
public void uploadFileWithNonASCIIName_HttpClient() throws Exception {
    final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt";
    final String path = getClass().getClassLoader().getResource(filename).toExternalForm();
    final File file = new File(new URI(path));
    assertTrue(file.exists());

    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload2", Upload2Servlet.class);

    startWebServer("./", null, servlets);
    final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"));
    builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));

    filePost.setEntity(builder.build());

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    final HttpResponse httpResponse = clientBuilder.build().execute(filePost);

    InputStream content = null;
    try {
        content = httpResponse.getEntity().getContent();
        final String response = new String(IOUtils.toByteArray(content));
        //this is the value with ASCII encoding
        assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response));
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:com.github.aistomin.http.PostRequest.java

@Override
public String execute() throws Exception {
    final Request request = Request.Post(this.resource);
    for (final Map.Entry<String, String> item : this.heads.entrySet()) {
        request.addHeader(item.getKey(), item.getValue());
    }//w w  w . jav  a 2  s  .co  m
    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new LaxRedirectStrategy());
    builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
        public boolean retryRequest(final HttpResponse response, final int count, final HttpContext context) {
            return count <= PostRequest.RETRY_COUNT;
        }

        public long getRetryInterval() {
            return PostRequest.RETRY_INTERVAL;
        }
    });
    return Executor.newInstance(builder.build()).execute(request).returnContent().asString();
}

From source file:com.datatorrent.stram.util.WebServicesClient.java

public WebServicesClient(ClientConfig config) {
    if (SecurityUtils.isHadoopWebSecurityEnabled()) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(connectionManager);
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setDefaultAuthSchemeRegistry(authRegistry);
        ApacheHttpClient4Handler httpClientHandler = new ApacheHttpClient4Handler(httpClientBuilder.build(),
                new BasicCookieStore(), false);
        client = new Client(httpClientHandler, config);
    } else {// ww w .  j  a va 2  s  . c o m
        client = Client.create(config);
    }
}

From source file:org.jboss.teiid.quickstart.PortfolioClient.java

public void resteasyHttpBackendClient() {

    System.out.println("\nResteasy Client API with HTTP client as engine");

    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    // 1. Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // 2. Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // 3. Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    // 4. Create client executor and proxy
    HttpClientBuilder builder = HttpClientBuilder.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    credsProvider.setCredentials(scope, credentials);
    builder.setDefaultCredentialsProvider(credsProvider);
    HttpClient httpClient = builder.build();

    // 5. Create ResteasyClient with http client as engine
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

    // 6. Execute Rest call via ResteasyClient
    String authString = getBasicAuthentication();
    for (String api : apis) {
        ResteasyWebTarget target = client.target(api);
        Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML)
                .header(HttpHeaders.AUTHORIZATION, authString).get();
        if (response.getStatus() == 200) {
            String value = response.readEntity(String.class);
            System.out.println(value);
            response.close();/*from w  w  w.j  av a 2s  .c om*/
        } else {
            handleError(response);
        }
    }
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

@Override
public void init() throws RepositoryException {
    super.init();
    if (httpFactory != null) {
        HttpClientBuilder clientBuilder = httpFactory.newBuilder();
        clientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(timeout).build());
        httpClient = clientBuilder.build();
    }//from   w w w .j a va 2  s  .c o m
}

From source file:de.bytefish.fcmjava.client.http.apache.DefaultHttpClient.java

public DefaultHttpClient(IFcmClientSettings settings, IJsonSerializer serializer,
        HttpClientBuilder httpClientBuilder) {

    if (settings == null) {
        throw new IllegalArgumentException("settings");
    }//w w  w  .ja v a2 s  .  com

    if (httpClientBuilder == null) {
        throw new IllegalArgumentException("httpClientBuilder");
    }

    if (serializer == null) {
        throw new IllegalArgumentException("serializer");
    }

    this.settings = settings;
    this.serializer = serializer;
    this.client = httpClientBuilder.build();
}

From source file:net.sf.jasperreports.phantomjs.ProcessConnection.java

public ProcessConnection(ProcessDirector director, PhantomJSProcess process) {
    this.process = process;

    HttpClientBuilder clientBuilder = HttpClients.custom();

    // single connection
    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
    clientBuilder.setConnectionManager(connManager);

    RequestConfig requestConfig = RequestConfig.custom()
            // ignore cookies for now
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).setSocketTimeout(director.getRequestTimeout()).build();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    this.httpClient = clientBuilder.build();
}

From source file:com.cloudera.livy.client.http.LivyConnection.java

LivyConnection(URI uri, final HttpConf config) {
    HttpClientContext ctx = HttpClientContext.create();
    int port = uri.getPort() > 0 ? uri.getPort() : 8998;

    String path = uri.getPath() != null ? uri.getPath() : "";
    this.uriRoot = path + "/clients";

    RequestConfig reqConfig = new RequestConfig() {
        @Override//from  w w w.ja  v  a2  s  .  com
        public int getConnectTimeout() {
            return (int) config.getTimeAsMs(CONNETION_TIMEOUT);
        }

        @Override
        public int getSocketTimeout() {
            return (int) config.getTimeAsMs(SOCKET_TIMEOUT);
        }
    };

    HttpClientBuilder builder = HttpClientBuilder.create().disableAutomaticRetries().evictExpiredConnections()
            .evictIdleConnections(config.getTimeAsMs(CONNECTION_IDLE_TIMEOUT), TimeUnit.MILLISECONDS)
            .setConnectionManager(new BasicHttpClientConnectionManager())
            .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()).setDefaultRequestConfig(reqConfig)
            .setMaxConnTotal(1).setUserAgent("livy-client-http");

    this.server = uri;
    this.client = builder.build();
    this.mapper = new ObjectMapper();
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

/**
 * @param url//from   ww w . j  ava 2 s  .  c o m
 *            like "http://host/of/wiki/"
 */
public HttpActionClient(final HttpClientBuilder clientBuilder, final URL url) {
    this.url = url;
    path = pathOf(url);
    host = newHost(url);
    rateLimiter = Optional.absent();
    this.client = clientBuilder.build();
}