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

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

Introduction

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

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:org.wso2.am.integration.tests.rest.MalformedRequestTest.java

@Test(groups = "wso2.am", description = "Check if a malformed request breaks the system")
public void testMalformedPostWithMessageBuilding() {

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(getGatewayURLNhttp() + "response");

    httppost.addHeader(new Header() {
        @Override/*ww w  .  j  av a  2 s . co  m*/
        public String getName() {
            return "Content-Type";
        }

        @Override
        public String getValue() {
            return "application/xml";
        }

        @Override
        public HeaderElement[] getElements() throws ParseException {
            return new HeaderElement[0];
        }
    });

    String malformedBody = "<request>Request<request>";
    HttpResponse response = null;

    try {
        HttpEntity entity = new ByteArrayEntity(malformedBody.getBytes("UTF-8"));
        httppost.setEntity(entity);
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    } catch (UnsupportedEncodingException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    } catch (IOException e) {
        //Fail the test case.
        Assert.assertTrue(false, e.getMessage());
    }

    Assert.assertNotNull(response, "Received null response for malformed post");

    Assert.assertEquals(response.getStatusLine().getStatusCode(), 500,
            "Did not receive an http 500 for the malformed request");
}

From source file:com.linemetrics.monk.api.ApiClient.java

public ApiClient(String uri, ICredentials creds) throws RestException {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(OPERATION_TIME_OUT)
            .setConnectionRequestTimeout(CONNECTION_TIME_OUT).setSocketTimeout(SOCKET_TIME_OUT).build();
    HttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

    restclient = new RestClient(httpclient, creds, URI.create(uri));

    creds.initialize(this);
}

From source file:nl.jk_5.nailed.plugin.nmm.NmmMappack.java

@Override
public void prepareWorld(File destination, SettableFuture<Void> future) {
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {// w  w w  . java2  s. co  m
        String mappack = this.path.split("/", 2)[1];
        HttpGet request = new HttpGet("http://nmm.jk-5.nl/" + this.path + "/versions.json");
        HttpResponse response = httpClient.execute(request);
        MappackInfo list = NmmPlugin.gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"),
                MappackInfo.class);

        HttpGet request2 = new HttpGet(
                "http://nmm.jk-5.nl/" + this.path + "/" + mappack + "-" + list.latest + ".zip");
        HttpEntity response2 = httpClient.execute(request2).getEntity();
        if (response2 != null) {
            File mappackZip = new File(destination, "mappack.zip");
            try (ReadableByteChannel source = Channels.newChannel(response2.getContent());
                    FileChannel out = FileChannel.open(mappackZip.toPath(), StandardOpenOption.CREATE_NEW,
                            StandardOpenOption.WRITE)) {
                out.transferFrom(source, 0, Long.MAX_VALUE);
            }
            ZipUtils.extract(mappackZip, destination);
            mappackZip.delete();
            this.dir = destination;
            File dataDir = new File(destination, ".data");
            dataDir.mkdir();
            File metadataLocation = new File(dataDir, "game.xml");
            new File(destination, "game.xml").renameTo(metadataLocation);
            new File(destination, "scripts").renameTo(new File(dataDir, "scripts"));
            File worldsDir = new File(destination, "worlds");
            for (File f : worldsDir.listFiles()) {
                f.renameTo(new File(destination, f.getName()));
            }
            worldsDir.delete();
            //metadata = XmlMappackMetadata.fromFile(metadataLocation);
            future.set(null);
        } else {
            future.setException(new RuntimeException(
                    "Got an empty response while downloading mappack " + this.path + " from nmm.jk-5.nl"));
        }
    } catch (Exception e) {
        future.setException(
                new RuntimeException("Was not able to download mappack " + this.path + " from nmm.jk-5.nl", e));
    }
}

From source file:org.everit.osgi.authentication.cas.tests.SecureHttpClient.java

public SecureHttpClient(final String principal, final BundleContext bundleContext) throws Exception {
    this.principal = principal;

    httpClientContext = HttpClientContext.create();
    httpClientContext.setCookieStore(new BasicCookieStore());

    KeyStore trustStore = KeyStore.getInstance("jks");
    trustStore.load(bundleContext.getBundle().getResource("/jetty-keystore").openStream(),
            "changeit".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, new SecureRandom());

    httpClient = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:jatoo.weather.openweathermap.JaTooWeatherOpenWeatherMap.java

@Override
protected final String getJSONResponse(final String city) throws IOException {

    CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();//  w  ww .  j a  va 2s . c om
    HttpGet request = new HttpGet(URL_CURRENT_WEATHER + "?appid=" + appid + "&id=" + city + "&units=metric");
    CloseableHttpResponse response = client.execute(request);
    BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());

    return EntityUtils.toString(entity, "UTF-8");
}

From source file:de.bytefish.fcmjava.client.FcmClient.java

public FcmClient(IFcmClientSettings settings) {

    if (settings == null) {
        throw new IllegalArgumentException("settings");
    }/*from   ww  w . j  av  a  2  s .c o  m*/

    this.settings = settings;

    // Construct the Builder for all Requests:
    this.httpClientBuilder = HttpClientBuilder.create()
            // Build Request Pipeline:
            .addInterceptorFirst(new AuthenticationRequestInterceptor(settings.getApiKey()))
            .addInterceptorLast(new JsonRequestInterceptor())
            .addInterceptorLast(new LoggingRequestInterceptor())
            // Build Response Pipeline:
            .addInterceptorFirst(new LoggingResponseInterceptor())
            .addInterceptorLast(new StatusResponseInterceptor());
}

From source file:objective.taskboard.it.TemplateIT.java

@Before
public void login() throws IOException, URISyntaxException {
    client = HttpClientBuilder.create().build();
    session = doLogin(client);
}

From source file:org.xwiki.contrib.xwiki.rest.test.TestServer.java

/**
 * @return if the server is running and ready
 * @throws IOException if error occurs//from   ww  w .j  a  va 2 s . co  m
 */
public boolean isServerRunning() throws IOException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("http://localhost:9000/isrunning");
        client.execute(request);
        return true;
    } catch (HttpHostConnectException e) {
        return false;
    }
}

From source file:com.predic8.membrane.examples.tests.integration.OAuth2RaceCondition.java

@Test
public void testSessionIdStateRaceCondition() throws Exception {
    HttpClient hc = HttpClientBuilder.create().build();

    login(hc);/*from w w w  . j a  va2s. com*/
    System.out.println("Logged in");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 10; i++) {

        //            HttpClient hc1 = HttpClientBuilder.create().build();
        //            login(hc1);
        Future<Exception>[] results = new Future[2];

        int parallelReqs = 2;
        CountDownLatch cdl = new CountDownLatch(parallelReqs);

        for (int j = 0; j < parallelReqs; j++) {
            final int fj = j;
            results[j] = executor.submit(() -> {
                try {
                    int uri = (fj % 2 == 0 ? 1 : 2);
                    String url = "http://localhost:2011/test" + uri;
                    HttpGet get = new HttpGet(url);
                    //setNoRedirects(get);
                    cdl.countDown();
                    cdl.await();
                    try (CloseableHttpResponse getRes = (CloseableHttpResponse) hc.execute(get)) {
                        assertEquals(200, getRes.getStatusLine().getStatusCode());
                        String resText = EntityUtils.toString(getRes.getEntity(), "UTF-8");
                        System.out.println("Called: Test" + uri + ".\nActual: " + resText);
                        assertTrue(resText.contains(Integer.toString(uri)));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            });
        }
        for (int j = 0; j < parallelReqs; j++) {
            results[j].get();
        }

        for (int j = 0; j < parallelReqs; j++) {
            Exception e = results[j].get();
            if (e != null)
                throw new RuntimeException(e);
        }

    }
    executor.shutdown();
}

From source file:com.aspectran.jetty.JettyServerTest.java

@Test
void testHello() throws IOException {
    Translet translet = aspectran.translate("/hello");
    String result1 = translet.toString();
    String result2;/*  w w w .j a v  a  2s  .  co  m*/

    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet("http://127.0.0.1:8099/hello_jsp");
        HttpResponse response = client.execute(request);
        result2 = new BasicResponseHandler().handleResponse(response).trim();
    } catch (SocketException e) {
        // Network is unreachable
        return;
    }

    assertEquals(result1, result2);
}