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:ch.ralscha.extdirectspring_itest.SecuredServiceTest.java

@Test
public void callSetDate() throws IOException, JsonParseException, JsonMappingException {

    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {//from w w w . j a  va  2  s.co  m

        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        StringEntity postEntity = new StringEntity(
                "{\"action\":\"securedService\",\"method\":\"setDate\",\"data\":[102,\"26/04/2012\"],\"type\":\"rpc\",\"tid\":1}",
                "UTF-8");

        post.setEntity(postEntity);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        assertThat(responseString).isNotNull();
        assertThat(responseString.startsWith("[") && responseString.endsWith("]")).isTrue();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper
                .readValue(responseString.substring(1, responseString.length() - 1), Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("result")).isEqualTo("102,26.04.2012,");
        assertThat(rootAsMap.get("method")).isEqualTo("setDate");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("securedService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.mycompany.horus.ServiceListener.java

private String getWsdlParametros() throws IOException {
    String resp;/*  ww  w .  j a  v  a 2  s. c  o m*/
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(PARAMETERS_URL);
    HttpResponse response = httpclient.execute(post);
    HttpEntity respEntity = response.getEntity();
    resp = EntityUtils.toString(respEntity);
    return resp;
}

From source file:de.utkast.encoding.EncodingTestClient.java

@Test
public void testEncoding() throws Exception {

    String input = "?? ?";
    String url = "http://localhost:8080/restful-encoding/enc";

    EncodingDTO dto = new EncodingDTO(input);

    JAXBContext ctx = JAXBContext.newInstance(EncodingDTO.class);
    StringWriter writer = new StringWriter();
    ctx.createMarshaller().marshal(dto, writer);

    System.out.println(String.format("Will send: %s", writer.toString()));

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    HttpEntity entity = new ByteArrayEntity(writer.toString().getBytes("UTF-8"));
    post.setEntity(entity);//ww w . jav  a2 s  . co  m
    post.setHeader("Content-Type", "application/xml;charset=UTF-8");
    post.setHeader("Accept", "application/xml;charset=UTF-8");

    HttpResponse response = client.execute(post);
    String output = EntityUtils.toString(response.getEntity(), "UTF-8");

    assertEquals(writer.toString(), output);
}

From source file:mobi.jenkinsci.alm.trello.test.TrelloClientTest.java

@Before
public void setUp() throws Exception {
    client = new TrelloClient(new TrelloPluginConfig("https://trello.com"), 1L, new HttpClientFactory() {

        @Override// w w w  .j  a v a2s .c  o m
        public HttpClient getHttpClient() {
            return HttpClientBuilder.create().build();
        }

        @Override
        public HttpClient getBasicAuthHttpClient(URL url, String user, String password)
                throws MalformedURLException {
            return getHttpClient();
        }
    });

}

From source file:org.kaaproject.kaa.server.common.admin.HttpComponentsRequestFactoryBasicAuth.java

private static HttpClient createHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(DEFAULT_MAX_TOTAL_CONNECTIONS)
            .setMaxConnPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE)
            .setRetryHandler(new BasicHttpRequestRetryHandler(5, 10000))
            .setServiceUnavailableRetryStrategy(new BaseServiceUnavailableRetryStrategy(3, 5000)).build();
    return httpClient;
}

From source file:de.yaio.commons.http.HttpUtils.java

/** 
 * execute the prepared Request//  w w  w  .ja  v  a2  s.c  o  m
 * @param request                request to call
 * @param username               username for auth
 * @param password               password for auth
 * @return                       HttpResponse
 * @throws ClientProtocolException possible Exception if Request-state <200 > 299 
 * @throws IOException            possible Exception if Request-state <200 > 299
 */
public static HttpResponse executeRequest(final HttpUriRequest request, final String username,
        final String password) throws ClientProtocolException, IOException {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    HttpResponse response = client.execute(request);
    return response;
}

From source file:cr.ac.siua.tec.services.impl.RTServiceImpl.java

/**
 * Returns all of the ticket's data in a hashmap. If the ticket doesn't exist returns null.
 *//*from   ww  w  . j  av a  2  s .c  o  m*/
public HashMap<String, String> getTicket(String ticketId) {
    HashMap<String, String> ticketContent = null;
    String url = this.baseUrl + "/ticket/" + ticketId + "/show";

    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("user", this.rtUser));
        urlParameters.add(new BasicNameValuePair("pass", this.rtPw));
        StringBuilder requestUrl = new StringBuilder(url);
        String queryString = URLEncodedUtils.format(urlParameters, "utf-8");
        requestUrl.append("?");
        requestUrl.append(queryString);

        HttpGet get = new HttpGet(requestUrl.toString());
        HttpResponse response = client.execute(get);
        String responseString = getResponseString(response);
        ticketContent = ticketStringToHashMap(responseString);
        return ticketContent;
    } catch (IOException e) {
        System.out.println("Exception while trying to get RT Ticket using GET.");
        e.printStackTrace();
        return null;
    }
}

From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java

/**
 * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
 * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
 *
 * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
 * certificates.//from   ww  w  .  jav a2  s .  com
 *
 * @param restTemplate Must not be null
 * @param username Can be null
 * @param password Can be null
 * @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
 */
public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password,
        boolean skipSslValidation) {

    Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    if (skipSslValidation) {
        httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    final CloseableHttpClient httpClient = httpClientBuilder.build();
    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    restTemplate.setRequestFactory(requestFactory);
}