Java Code Examples for org.apache.http.impl.client.HttpClientBuilder

The following are top voted examples for showing how to use org.apache.http.impl.client.HttpClientBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: scouter-pulse-aws-monitor   File: GetMonitoringInstances.java   Source Code and License 13 votes vote down vote up
private void register(RegisterModel model) throws Exception {
	String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register";
	
       String param = new Gson().toJson(model);

       HttpPost post = new HttpPost(url);
       post.addHeader("Content-Type","application/json");
       post.setEntity(new StringEntity(param));
     
       CloseableHttpClient client = HttpClientBuilder.create().build();
     
       // send the post request
       HttpResponse response = client.execute(post);
       
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
       		logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay());
       } else {
        	logger.warn("Register message sent failed. Verify below information.");
        	logger.warn("[URL] : " + url);
        	logger.warn("[Message] : " + param);
        	logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8"));
       }
}
 
Example 2
Project: mapr-music   File: CoverArtArchiveClient.java   Source Code and License 7 votes vote down vote up
private void ensureApiCalled() {

        if (!this.available) {
            return;
        }

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet(RELEASE_COVERS_ENDPOINT + releaseId);
        getRequest.addHeader("accept", "application/json");

        try {

            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                this.available = false;
                return;
            }

            this.coverArtResponse = mapper.readValue(response.getEntity().getContent(), CoverArtArchiveResponse.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 3
Project: pprxmtr   File: Handler.java   Source Code and License 7 votes vote down vote up
private void sendSlackImageResponse(ObjectNode json, String s3Key) {
	try {
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode message = mapper.createObjectNode();
		ArrayNode attachments = mapper.createArrayNode();
		ObjectNode attachment = mapper.createObjectNode();

		String emoji = json.get("text").asText();

		if (UrlValidator.getInstance().isValid(emoji)) {
			attachment.put("title_link", emoji);
			emoji = StringUtils.substringAfterLast(emoji, "/");
		}

		String username = json.get("user_name").asText();
		String responseUrl = json.get("response_url").asText();
		String slackChannelId = json.get("channel_id").asText();
		String imageUrl = String.format("https://s3.amazonaws.com/%s/%s", PROPERTIES.getProperty(S3_BUCKET_NAME), s3Key);

		message.put("response_type", "in_channel");
		message.put("channel_id", slackChannelId);
		attachment.put("title", resolveMessage("slackImageResponse", emoji, username));
		attachment.put("fallback", resolveMessage("approximated", emoji));
		attachment.put("image_url", imageUrl);
		attachments.add(attachment);
		message.set("attachments", attachments);

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost slackResponseReq = new HttpPost(responseUrl);
		slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(message), ContentType.APPLICATION_JSON));
		HttpResponse slackResponse = client.execute(slackResponseReq);
		int status = slackResponse.getStatusLine().getStatusCode();
		LOG.info("Got {} status from Slack API after sending approximation to response url.", status);
	} catch (UnsupportedOperationException | IOException e) {
		LOG.error("Exception occured when sending Slack response", e);
	}
}
 
Example 4
Project: ats-framework   File: HttpClient.java   Source Code and License 7 votes vote down vote up
/**
 * Setup SSL. Pass the trusted certificates and client private key and certificate,
 * if applicable.
 *
 * @param httpClientBuilder The client builder
 * @throws HttpException
 */
private void setupSSL( HttpClientBuilder httpClientBuilder ) throws HttpException {

    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        // set trust material
        if (trustedServerCertificates != null && trustedServerCertificates.length > 0) {
            sslContextBuilder.loadTrustMaterial(convertToKeyStore(trustedServerCertificates),
                                                new TrustStrategy() {

                                                    @Override
                                                    public boolean isTrusted( X509Certificate[] chain,
                                                                              String authType ) throws CertificateException {

                                                        return checkIsTrusted(chain);
                                                    }
                                                });

        } else {
            // no trust material provided, we will trust no matter the remote party
            sslContextBuilder.loadTrustMaterial(
                                                new TrustStrategy() {
                                                    @Override
                                                    public boolean
 
Example 5
Project: datax   File: RetryUtilTest.java   Source Code and License 6 votes vote down vote up
@Ignore
    public void testRetryAsync3() throws Exception {
        final int TIME_OUT = 30000;
        ThreadPoolExecutor executor = RetryUtil.createThreadPoolExecutor();
        String res = RetryUtil.asyncExecuteWithRetry(new Callable<String>() {
            @Override
            public String call() throws Exception {
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT)
                        .setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT)
                        .setStaleConnectionCheckEnabled(true).build();

                HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(10).setMaxConnPerRoute(10)
                        .setDefaultRequestConfig(requestConfig).build();

                HttpGet httpGet = new HttpGet();
                httpGet.setURI(new URI("http://0.0.0.0:8080/test"));
                httpClient.execute(httpGet);
                return OK;
            }
        }, 3, 1000L, false, 6000L, executor);
        Assert.assertEquals(res, OK);
//        Assert.assertEquals(RetryUtil.EXECUTOR.getActiveCount(), 0);
    }
 
Example 6
Project: smarti   File: RocketChatEndpoint.java   Source Code and License 6 votes vote down vote up
public RocketChatEndpoint(
        @Value("${rocketchat.proxy.hostname:}") String proxyHostname,
        @Value("${rocketchat.proxy.port:80}") int proxyPort,
        @Value("${rocketchat.proxy.scheme:http}") String proxyScheme
) {

    httpClientBuilder = HttpClientBuilder.create()
            .setRetryHandler((exception, executionCount, context) -> executionCount < 3)
            .setConnectionBackoffStrategy(new ConnectionBackoffStrategy() {
                @Override
                public boolean shouldBackoff(Throwable t) {
                    return t instanceof IOException;
                }

                @Override
                public boolean shouldBackoff(HttpResponse resp) {
                    return false;
                }
            })
            .setUserAgent("Smarti/0.0 Rocket.Chat-Endpoint/0.1");

    if(StringUtils.isNotBlank(proxyHostname)) {
        httpClientBuilder.setProxy(new HttpHost(proxyHostname, proxyPort, proxyScheme));
    }
}
 
Example 7
Project: nifi-atlas   File: NiFiApiClient.java   Source Code and License 6 votes vote down vote up
private String getEntity(URI url) throws IOException {
    final HttpGet get = new HttpGet(url);
    get.setConfig(requestConfig);
    get.setHeader("Accept", "application/json");

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (sslContext != null) {
        clientBuilder.setSslcontext(sslContext);
    }

    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        try (CloseableHttpResponse response = httpClient.execute(get)) {

            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (200 != statusCode) {
                final String msg = String.format("Failed to get entity from %s, response=%d:%s",
                        get.getURI(), statusCode, statusLine.getReasonPhrase());
                throw new RuntimeException(msg);
            }
            final HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
    }
}
 
Example 8
Project: url-to-google-drive   File: GoogleOauthController.java   Source Code and License 6 votes vote down vote up
private User getUser(@NotNull Token token) throws IOException, URISyntaxException {

		URIBuilder builder = new URIBuilder(PROFILE_URL);
		builder.addParameter("access_token", token.getAccessToken());

		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(builder.build());
		org.apache.http.HttpResponse response = httpClient.execute(httpGet);
		int statusCode = response.getStatusLine().getStatusCode();
		InputStream inputStream = response.getEntity().getContent();

		if (HttpUtilities.success(statusCode)) {
			User user = gson.fromJson(new InputStreamReader(inputStream), User.class);
			user.setToken(token);
			return user;
		}

		throw new ApiException(HttpStatus.valueOf(statusCode));
	}
 
Example 9
Project: bubble2   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
private HttpUtils(HttpRequestBase request) {
	this.request = request;

	this.clientBuilder = HttpClientBuilder.create();
	this.isHttps = request.getURI().getScheme().equalsIgnoreCase("https");
	this.config = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);
	this.cookieStore = new BasicCookieStore();

	if (request instanceof HttpPost) {
		this.type = 1;
		this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());

	} else if (request instanceof HttpGet) {
		this.type = 2;
		this.uriBuilder = new URIBuilder();

	} else if (request instanceof HttpPut) {
		this.type = 3;
		this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>());

	} else if (request instanceof HttpDelete) {
		this.type = 4;
		this.uriBuilder = new URIBuilder();
	}
}
 
Example 10
Project: url-to-google-drive   File: GoogleOauthController.java   Source Code and License 6 votes vote down vote up
private Token getAccessToken(@NotNull String code) throws IOException {
	// Initialize client
	HttpClient httpClient = HttpClientBuilder.create().build();
	HttpPost httpPost = new HttpPost(TOKEN_URL);

	// add request parameters
	List<NameValuePair> parameters = new ArrayList<>();
	parameters.add(new BasicNameValuePair("code", code));
	parameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
	parameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
	parameters.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
	parameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
	httpPost.setEntity(new UrlEncodedFormEntity(parameters));

	// send request
	org.apache.http.HttpResponse response = httpClient.execute(httpPost);
	int statusCode = response.getStatusLine().getStatusCode();
	InputStream inputStream = response.getEntity().getContent();

	if (HttpUtilities.success(statusCode))
		return gson.fromJson(new InputStreamReader(inputStream), Token.class);

	throw new ApiException(HttpStatus.valueOf(statusCode));
}
 
Example 11
Project: pprxmtr   File: Handler.java   Source Code and License 6 votes vote down vote up
private void sendSlackTextResponse(ObjectNode json, String message) {
	try {
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode messageNode = mapper.createObjectNode();

		String responseUrl = json.get("response_url").asText();
		String slackChannelId = json.get("channel_id").asText();

		messageNode.put("text", message);
		messageNode.put("channel_id", slackChannelId);

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost slackResponseReq = new HttpPost(responseUrl);
		slackResponseReq.setEntity(new StringEntity(mapper.writeValueAsString(messageNode), ContentType.APPLICATION_JSON));
		HttpResponse slackResponse = client.execute(slackResponseReq);
		int status = slackResponse.getStatusLine().getStatusCode();
		LOG.info("Got {} status from Slack API after sending request to response url.", status);
	} catch (UnsupportedOperationException | IOException e) {
		LOG.error("Exception occured when sending Slack response", e);
	}
}
 
Example 12
Project: allure-java   File: HttpClientAttachmentTest.java   Source Code and License 6 votes vote down vote up
@Test
void httpClientAttachmentTest() throws IOException {
    stubFor(get(urlEqualTo("/hello"))
            .willReturn(aResponse()
                    .withBody("Hello world!")));

    final HttpClientBuilder builder = HttpClientBuilder.create()
            .addInterceptorFirst(new AllureHttpClientRequest())
            .addInterceptorLast(new AllureHttpClientResponse());
    try (CloseableHttpClient httpClient = builder.build()) {
        final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port()));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            response.getStatusLine().getStatusCode();
        }
    }
}
 
Example 13
Project: allure-java   File: AllureHttpClientTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldCreateRequestAttachment() throws Exception {
    final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class);
    final AttachmentProcessor<AttachmentData> processor = mock(AttachmentProcessor.class);

    final HttpClientBuilder builder = HttpClientBuilder.create()
            .addInterceptorLast(new AllureHttpClientRequest(renderer, processor));

    try (CloseableHttpClient httpClient = builder.build()) {
        final HttpGet httpGet = new HttpGet(String.format("http://localhost:%d/hello", server.port()));
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            response.getStatusLine().getStatusCode();
        }
    }

    final ArgumentCaptor<AttachmentData> captor = ArgumentCaptor.forClass(AttachmentData.class);
    verify(processor, times(1))
            .addAttachment(captor.capture(), eq(renderer));

    assertThat(captor.getAllValues())
            .hasSize(1)
            .extracting("url")
            .containsExactly("/hello");
}
 
Example 14
Project: minsx-java-example   File: RemoteServerClientImpl.java   Source Code and License 6 votes vote down vote up
@Test
public void testPost() throws IOException {
    String ip = "冰箱冰箱冰箱冰箱冰箱冰箱冰箱";
    // 创建HttpClientBuilder
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // HttpClient
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    // 请求参数
    StringEntity entity = new StringEntity("", DEFAULT_ENCODE);
    entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
    HttpPost httpPost = new HttpPost("https://m.fangliaoyun.com");
    httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
    //此处区别PC终端类型
    httpPost.addHeader("typeFlg", "9");
    //此处增加浏览器端访问IP
    httpPost.addHeader("x-forwarded-for", ip);
    httpPost.addHeader("Proxy-Client-IP", ip);
    httpPost.addHeader("WL-Proxy-Client-IP", ip);
    httpPost.addHeader("HTTP_CLIENT_IP", ip);
    httpPost.addHeader("X-Real-IP", ip);
    httpPost.addHeader("Host", ip);
    httpPost.setEntity(entity);
    httpPost.setConfig(RequestConfig.DEFAULT);

    HttpResponse httpResponse;
    // post请求
    httpResponse = closeableHttpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    System.out.println(httpEntity.getContent());
    //释放资源
    closeableHttpClient.close();
}
 
Example 15
Project: groupsio-api-java   File: BaseResource.java   Source Code and License 6 votes vote down vote up
/**
 * Get a valid {@link HttpClient} to use, with a valid token.
 * 
 * @param login
 * @return
 */
private CloseableHttpClient getHttpClient(final Boolean login, final HttpUriRequest request)
{
    final HttpClientBuilder builder = HttpClientBuilder.create();
    String key;
    // if (apiClient.getApiToken() == null || apiClient.getApiToken())
    if (login)
    {
        key = apiClient.getApiKey();
    }
    else
    {
        key = apiClient.getApiToken();
    }
    key += ":";
    final byte[] credentials = Base64.encodeBase64(key.getBytes(StandardCharsets.UTF_8));
    final BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
    request.addHeader(authHeader);
    return builder.build();
}
 
Example 16
Project: teamcity-msteams-notifier   File: MsTeamsNotificationImpl.java   Source Code and License 6 votes vote down vote up
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));
              
          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }
          
          this.client = clientBuilder.build();
}
  }
 
Example 17
Project: mxhsd   File: HttpFederationClient.java   Source Code and License 6 votes vote down vote up
public HttpFederationClient(HomeserverState global, FederationDomainResolver resolver) {
    this.global = global;
    this.resolver = resolver;

    try {
        SocketConfig sockConf = SocketConfig.custom().setSoTimeout(30000).build();
        // FIXME properly handle SSL context by validating certificate hostname
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustAllStrategy()).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        this.client = HttpClientBuilder.create()
                .disableAuthCaching()
                .disableAutomaticRetries()
                .disableCookieManagement()
                .disableRedirectHandling()
                .setDefaultSocketConfig(sockConf)
                .setSSLSocketFactory(sslSocketFactory)
                .setUserAgent(global.getAppName() + "/" + global.getAppVersion())
                .build();
    } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Project: desafio-pagarme   File: Client.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the security rest template.
 *
 * @throws KeyManagementException the key management exception
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException the key store exception
 */
private void createSecurityRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException{
	TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
	SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
	        .loadTrustMaterial(null, acceptingTrustStrategy)
	        .build();
	SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
	
	HttpComponentsClientHttpRequestFactory requestFactory =
	        new HttpComponentsClientHttpRequestFactory();
	
	 HttpClient httpClient = HttpClientBuilder.create()
               .disableCookieManagement()
               .useSystemProperties()
               .setSSLSocketFactory(csf)
               .build();
	requestFactory.setHttpClient(httpClient);
	this.restTemplate = new RestTemplate(requestFactory);
}
 
Example 19
Project: crnk-framework   File: HttpClientAdapter.java   Source Code and License 6 votes vote down vote up
private HttpClientBuilder createBuilder() {
	// brave enforces this, hopefully can be removed again eventually

	HttpClientBuilder builder = null;
	for (HttpClientAdapterListener listener : listeners) {
		if (listener instanceof HttpClientBuilderFactory) {
			PreconditionUtil
					.assertNull("only one module can contribute a HttpClientBuilder with HttpClientBuilderFactory", builder);
			builder = ((HttpClientBuilderFactory) listener).createBuilder();
		}
	}

	if (builder != null) {
		return builder;
	}
	else {
		return HttpClients.custom();
	}

}
 
Example 20
Project: outcomes   File: RfiController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/rfi/weChat", method = RequestMethod.POST)
public void testPost(@RequestParam(value = "code", required = false) String code) throws IOException {
    System.out.println(code);
    System.out.println("====================================");

    String url = "https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect";
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
    CloseableHttpClient client = builder.build();
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    InputStream inputStream = response.getEntity().getContent();
    byte [] tt = new byte[1024];
    while (inputStream.read(tt) != -1) {
        System.out.println(new String(tt,"utf-8"));
    }
}
 
Example 21
Project: qonduit   File: HTTPStrictTransportSecurityIT.java   Source Code and License 6 votes vote down vote up
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
 
Example 22
Project: stock-api-sdk   File: ApiUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Initializes Http Client.
 *
 * @return Instance of HttpClient
 */
private static HttpClient initialize() {
    PoolingHttpClientConnectionManager connManager
            = new PoolingHttpClientConnectionManager();
    RequestConfig config = RequestConfig.custom()
            .setConnectionRequestTimeout(TIME_OUT)
            .setSocketTimeout(TIME_OUT).build();
    HttpClient httpClient = HttpClientBuilder.create()
            .setConnectionManager(connManager).disableRedirectHandling()
            .setDefaultRequestConfig(config).build();
    return httpClient;
}
 
Example 23
Project: security-karate   File: LoginExecutor.java   Source Code and License 5 votes vote down vote up
/**
 * Perform a http login and return the acquired session ID.
 *
 * @param credentials the credentials to login with
 * @param csrfToken   the csrfToken form the login page
 *
 * @param forwardedForHeader
 * @return the sessionId if login was successful
 *
 * @throws IOException
 */
private Optional<String> login(Credentials credentials, String csrfToken, Header forwardedForHeader) throws IOException {
    Optional<String> sessionId;
    CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    try {
        HttpPost httpPost = new HttpPost(configuration.getLoginUrl());
        httpPost.setHeader(forwardedForHeader);

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", credentials.getUsername()));
        nvps.add(new BasicNameValuePair("password", credentials.getPassword()));
        nvps.add(new BasicNameValuePair("_csrf", csrfToken));

        String initialSession = getCurrentSession(context);

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost, context);

        try {
            logger.debug(response2.getStatusLine().toString());
            sessionId = extractSessionId(context);
            if(initialSession != null && initialSession.equals(sessionId.orElse("nothing"))){
                return Optional.empty();
            }
        } finally {
            response2.close();
        }

    } finally {
        httpclient.close();
    }
    return sessionId;
}
 
Example 24
Project: Reer   File: HttpClientConfigurer.java   Source Code and License 5 votes vote down vote up
public void configure(HttpClientBuilder builder) {
    SystemDefaultCredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
    configureSslSocketConnectionFactory(builder, httpSettings.getSslContextFactory());
    configureAuthSchemeRegistry(builder);
    configureCredentials(builder, credentialsProvider, httpSettings.getAuthenticationSettings());
    configureProxy(builder, credentialsProvider, httpSettings);
    configureUserAgent(builder);
    builder.setDefaultCredentialsProvider(credentialsProvider);
}
 
Example 25
Project: Reer   File: HttpClientConfigurer.java   Source Code and License 5 votes vote down vote up
private void configureAuthSchemeRegistry(HttpClientBuilder builder) {
    builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory())
        .build()
    );
}
 
Example 26
Project: Reer   File: HttpClientConfigurer.java   Source Code and License 5 votes vote down vote up
private void configureProxy(HttpClientBuilder builder, CredentialsProvider credentialsProvider, HttpSettings httpSettings) {
    HttpProxySettings.HttpProxy httpProxy = httpSettings.getProxySettings().getProxy();
    HttpProxySettings.HttpProxy httpsProxy = httpSettings.getSecureProxySettings().getProxy();

    for (HttpProxySettings.HttpProxy proxy : Lists.newArrayList(httpProxy, httpsProxy)) {
        if (proxy != null) {
            if (proxy.credentials != null) {
                useCredentials(credentialsProvider, proxy.host, proxy.port, Collections.singleton(new AllSchemesAuthentication(proxy.credentials)));
            }
        }
    }
    builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
}
 
Example 27
Project: logistimo-web-service   File: RestConfig.java   Source Code and License 5 votes vote down vote up
private static ClientHttpRequestFactory getClientHttpRequestFactory() {
  int timeout = ConfigUtil.getInt("api.client.timeout", 5000);
  RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout)
      .setConnectionRequestTimeout(timeout)
      .setSocketTimeout(timeout)
      .build();
  CloseableHttpClient client = HttpClientBuilder
      .create()
      .setDefaultRequestConfig(config)
      .build();
  return new HttpComponentsClientHttpRequestFactory(client);
}
 
Example 28
Project: Patterdale   File: PatterdaleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void scrapesOracleDatabaseMetricsOnRequest() throws Exception {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(new HttpGet("http://localhost:7001/metrics"));

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    assertThat(responseBody(response)).matches(Pattern.compile(
            "database_up\\{database=\"bobsDatabase\",query=\"SELECT 1 FROM DUAL\"} 1.0\n" +
                    "database_up\\{database=\"alicesDatabase\",query=\"SELECT 1 FROM DUAL\"} 1.0\n" +
                    ".*"
            , Pattern.DOTALL)
    );
}
 
Example 29
Project: OnionHarvester   File: OH.java   Source Code and License 5 votes vote down vote up
public static synchronized Object[] getNewOnions() {
    Vector<Object> out = new Vector<>();

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(URLGenerate);

    // add request header
    request.addHeader("User-Agent", "OnionHarvester - Java Client");
    try {
        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            out.add(false);
            return out.toArray();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        String temp = result.toString();
        jobj = new JSONObject(temp);
        jobj.getJSONArray("ports").iterator().forEachRemaining(o -> {
            getPorts().add(Integer.valueOf((String) o));
        });
        out.add(true);
        out.add(jobj.getString("start"));
        out.add(jobj.getString("end"));
        out.add(jobj.getString("id"));
    } catch (Exception ex) {
        out.add(false);
    } finally {
        return out.toArray();
    }
}
 
Example 30
Project: cas-server-4.2.1   File: SimpleHttpClientFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * Build a HTTP client based on the current properties.
 *
 * @return the built HTTP client
 */
private CloseableHttpClient buildHttpClient() {
    try {

        final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;

        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();

        final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
        connMgmr.setMaxTotal(this.maxPooledConnections);
        connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
        connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT);

        final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
        final HttpRoute httpRoute = new HttpRoute(httpHost);
        connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);

        final RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(this.readTimeout)
                .setConnectTimeout(this.connectionTimeout)
                .setConnectionRequestTimeout(this.connectionTimeout)
                .setCircularRedirectsAllowed(this.circularRedirectsAllowed)
                .setRedirectsEnabled(this.redirectsEnabled)
                .setAuthenticationEnabled(this.authenticationEnabled)
                .build();


        final HttpClientBuilder builder = HttpClients.custom()
                .setConnectionManager(connMgmr)
                .setDefaultRequestConfig(requestConfig)
                .setSSLSocketFactory(sslsf)
                .setSSLHostnameVerifier(this.hostnameVerifier)
                .setRedirectStrategy(this.redirectionStrategy)
                .setDefaultCredentialsProvider(this.credentialsProvider)
                .setDefaultCookieStore(this.cookieStore)
                .setConnectionReuseStrategy(this.connectionReuseStrategy)
                .setConnectionBackoffStrategy(this.connectionBackoffStrategy)
                .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy)
                .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy)
                .setDefaultHeaders(this.defaultHeaders)
                .useSystemProperties();

        return builder.build();

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 31
Project: camunda-task-dispatcher   File: ExternalTaskRestServiceImpl.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {
    objectMapper = new ObjectMapper();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    if (StringUtils.hasText(camundaUser)) {
        final BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(camundaUser, camundaPass));
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    httpClient = clientBuilder.build();
}
 
Example 32
Project: sling-org-apache-sling-starter   File: SmokeIT.java   Source Code and License 5 votes vote down vote up
private CloseableHttpClient newClient() {

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
        credsProvider.setCredentials(new AuthScope("localhost", LAUNCHPAD_PORT), creds);

        return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();
    }
 
Example 33
Project: cas-5.1.0   File: SimpleHttpClientFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * Build a HTTP client based on the current properties.
 *
 * @return the built HTTP client
 */
private CloseableHttpClient buildHttpClient() {
    try {

        final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;

        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();

        final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
        connMgmr.setMaxTotal(this.maxPooledConnections);
        connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);
        connMgmr.setValidateAfterInactivity(DEFAULT_TIMEOUT);

        final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
        final HttpRoute httpRoute = new HttpRoute(httpHost);
        connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);

        final RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(this.readTimeout)
                .setConnectTimeout(Long.valueOf(this.connectionTimeout).intValue())
                .setConnectionRequestTimeout(Long.valueOf(this.connectionTimeout).intValue())
                .setCircularRedirectsAllowed(this.circularRedirectsAllowed)
                .setRedirectsEnabled(this.redirectsEnabled)
                .setAuthenticationEnabled(this.authenticationEnabled)
                .build();


        final HttpClientBuilder builder = HttpClients.custom()
                .setConnectionManager(connMgmr)
                .setDefaultRequestConfig(requestConfig)
                .setSSLSocketFactory(sslsf)
                .setSSLHostnameVerifier(this.hostnameVerifier)
                .setRedirectStrategy(this.redirectionStrategy)
                .setDefaultCredentialsProvider(this.credentialsProvider)
                .setDefaultCookieStore(this.cookieStore)
                .setConnectionReuseStrategy(this.connectionReuseStrategy)
                .setConnectionBackoffStrategy(this.connectionBackoffStrategy)
                .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy)
                .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy)
                .setDefaultHeaders(this.defaultHeaders)
                .useSystemProperties();

        return builder.build();

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
 
Example 34
Project: dcits-report   File: Start.java   Source Code and License 5 votes vote down vote up
/**
 * 每次报工结束,关闭该client,下次报工启用新的client
 */
private static void getHttpClient() {
	HttpClientUtils.closeQuietly(client);
	// Locale.setDefault(new Locale("zh","CN"));
	HttpClientBuilder builder = HttpClientBuilder.create();
	client = builder.build();
}
 
Example 35
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpPost post = new HttpPost("http://localhost:8088/refresh");
		HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
		CloseableHttpResponse response = builder.build().execute(post);
		System.out.println(EntityUtils.toString(response.getEntity()));
	}
 
Example 36
Project: TradingRobot   File: Trading.java   Source Code and License 5 votes vote down vote up
private int closeExistingTrade(String buyOrSell) {
	Trade t = getTrade();
	long existingTradeId;
	if (t != null) {
		if (t.getBuyOrSell().contentEquals(buyOrSell)) return 1;
		existingTradeId = t.getId();
	}
	else {
		//No trade is open
		return 0;
	}
	
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpPut request = new HttpPut(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/trades/"+existingTradeId+"/close");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	System.out.println(request.getURI());
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		System.out.println(resultJson);
		return response.getStatusLine().getStatusCode();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return 0;
	}
	
}
 
Example 37
Project: datarouter   File: DatarouterHttpClientBuilder.java   Source Code and License 5 votes vote down vote up
public DatarouterHttpClientBuilder(){
	this.retryHandler = new DatarouterHttpRetryHandler();
	this.timeoutMs = DEFAULT_TIMEOUT_MS;
	this.maxTotalConnections = DEFAULT_MAX_TOTAL_CONNECTION;
	this.maxConnectionsPerRoute = DEFAULT_MAX_CONNECTION_PER_ROUTE;
	this.httpClientBuilder = HttpClientBuilder.create()
			.setRetryHandler(retryHandler)
			.setRedirectStrategy(new LaxRedirectStrategy());
}
 
Example 38
Project: kafka-connect-marklogic   File: MarkLogicWriter.java   Source Code and License 5 votes vote down vote up
public MarkLogicWriter(final Map<String, String> config){
    
    connectionUrl = config.get(MarkLogicSinkConfig.CONNECTION_URL);
    user = config.get(MarkLogicSinkConfig.CONNECTION_USER);
    password = config.get(MarkLogicSinkConfig.CONNECTION_PASSWORD);
    
    requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5 * 1000).build();
    localContext = HttpClientContext.create();
    httpClient = HttpClientBuilder.create().build();
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    localContext.setCredentialsProvider(credentialsProvider);
    localContext.setRequestConfig(requestConfig);
}
 
Example 39
Project: ARCLib   File: SpnegoHelper.java   Source Code and License 5 votes vote down vote up
public static void addSpnego(HttpClientBuilder clientBuilder) {
    //Add spnego http header processor
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
    clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    //There has to be at least this dummy credentials provider or apache http client gives up
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials());
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
 
Example 40
Project: qonduit   File: HttpClient.java   Source Code and License 5 votes vote down vote up
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

    HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore)
            .setDefaultRequestConfig(defaultRequestConfig);
    if (hostVerificationEnabled) {
        builder.setSSLHostnameVerifier(new DefaultHostnameVerifier());
    } else {
        builder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return builder.build();
}
 
Example 41
Project: datax   File: HttpClientUtil.java   Source Code and License 5 votes vote down vote up
private void initApacheHttpClient() {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(HTTP_TIMEOUT_INMILLIONSECONDS)
            .setConnectTimeout(HTTP_TIMEOUT_INMILLIONSECONDS).setConnectionRequestTimeout(HTTP_TIMEOUT_INMILLIONSECONDS)
            .setStaleConnectionCheckEnabled(true).build();

      if(null == provider) {
          httpClient = HttpClientBuilder.create().setMaxConnTotal(POOL_SIZE).setMaxConnPerRoute(POOL_SIZE)
                  .setDefaultRequestConfig(requestConfig).build();
      } else {
          httpClient = HttpClientBuilder.create().setMaxConnTotal(POOL_SIZE).setMaxConnPerRoute(POOL_SIZE)
                  .setDefaultRequestConfig(requestConfig).setDefaultCredentialsProvider(provider).build();
      }
}
 
Example 42
Project: RoboInsta   File: InstagramContext.java   Source Code and License 5 votes vote down vote up
private CloseableHttpClient createHttpClient() {
    final RequestConfig requestConfig = RequestConfig.custom()
        .setCookieSpec(CookieSpecs.DEFAULT)
        .setAuthenticationEnabled(true)
        .setRedirectsEnabled(true)
        .build();
    return HttpClientBuilder.create()
        .setDefaultCookieStore(cookieStore)
        .setDefaultRequestConfig(requestConfig)
        .build();
}
 
Example 43
Project: webBee   File: HttpClientPool.java   Source Code and License 5 votes vote down vote up
/**
 * 根据配置自动生成需要的HTTP配置
 * @param setting
 * @return
 */
public HttpClientBuilder generateClient(Setting setting, HttpRequestBase httpMethod){
    RequestConfig requestConfig = RequestConfig.custom().build();
    HttpClientBuilder httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig);
    generateHeaders(httpMethod,setting);
    generateCookies(httpClient,setting);
    return httpClient;
}
 
Example 44
Project: hrrs   File: ApacheHttpClientFactory.java   Source Code and License 5 votes vote down vote up
private void setRedirectStrategy(HttpClientBuilder httpClientBuilder) {
    RedirectStrategy redirectStrategy = config.getRedirectStrategy().getImplementation();
    if (redirectStrategy == null) {
        httpClientBuilder.disableRedirectHandling();
    } else {
        httpClientBuilder.setRedirectStrategy(redirectStrategy);
    }
}
 
Example 45
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpPost post = new HttpPost("http://localhost:8088/refresh");
		HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
		CloseableHttpResponse response = builder.build().execute(post);
		System.out.println(EntityUtils.toString(response.getEntity()));
	}
 
Example 46
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClientBuilder builder = HttpClientBuilder.create();
//		HttpPost post = new HttpPost("http://localhost:8088/refresh");
		HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
		CloseableHttpResponse response = builder.build().execute(post);
		System.out.println(EntityUtils.toString(response.getEntity()));
	}
 
Example 47
Project: admin-shiro   File: RestTemplateConfig.java   Source Code and License 5 votes vote down vote up
/**
 * springboot初始化restTemplate
 */
@Bean
public RestTemplate initRestTemplate() {
    // 长连接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
    // 总连接数
    pollingConnectionManager.setMaxTotal(1000);
    // 同路由的并发数
    pollingConnectionManager.setDefaultMaxPerRoute(1000);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重试次数,默认是3次,没有开启
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // 保持长连接配置,需要在头添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectionRequestTimeout(200);
    builder.setConnectTimeout(5000);
    builder.setSocketTimeout(5000);

    RequestConfig requestConfig = builder.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));

    httpClientBuilder.setDefaultHeaders(headers);

    HttpClient httpClient = httpClientBuilder.build();

    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(5000);
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(5000);
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(200);
    // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
    clientHttpRequestFactory.setBufferRequestBody(false);

    // 添加内容转换器
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(initStringHttpMessageConverter());
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    return restTemplate;

}
 
Example 48
Project: java-restclient   File: HTTPCBuilder.java   Source Code and License 5 votes vote down vote up
@Override
protected ExecREST buildClient(RESTPool pool) throws IOException {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getDefault();
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    Registry<ConnectionSocketFactory> socketRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
            .build();

    //TODO buffers size
    SocketConfig socketConfig = SocketConfig.custom()
            .setSoTimeout(new Long(pool.getSocketTimeout()).intValue())
            .setTcpNoDelay(true)
            .setSoKeepAlive(true)
            .setSoReuseAddress(true)
            .build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setCharset(StandardCharsets.UTF_8)
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .build();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(),
            new DefaultHttpResponseParserFactory()
    );

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(new Long(pool.getMaxPoolWait()).intValue())
            .setConnectTimeout(new Long(pool.getConnectionTimeout()).intValue())
            .setExpectContinueEnabled(pool.expectContinue())
            .build();


    PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(socketRegistry, connFactory);

    ccm.setMaxTotal(pool.getMaxTotal());
    ccm.setDefaultMaxPerRoute(pool.getMaxPerRoute());
    ccm.setDefaultSocketConfig(socketConfig);
    ccm.setDefaultConnectionConfig(connectionConfig);
    ccm.setValidateAfterInactivity(pool.getValidationOnInactivity());

    HttpClientBuilder builder = HttpClients.custom()
            .setConnectionManager(ccm)
            .setDefaultRequestConfig(requestConfig)
            .disableAutomaticRetries()
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
            .disableCookieManagement()
            .disableContentCompression();

    addProxy(pool, builder);

    handleRedirects(pool, builder);

    CloseableHttpClient servClient = builder.build();

    IdleConnectionEvictor evictor = new IdleConnectionEvictor(ccm, pool.getEvictorSleep(), TimeUnit.MILLISECONDS, pool.getMaxIdleTime(), TimeUnit.MILLISECONDS);

    HTTPCClientMonitor monitor = pool.hasConnectionMetrics() ? new HTTPCSyncClientMonitor(pool.getName(), ccm) : null;

    return new HTTPCClient(servClient, evictor, monitor);
}
 
Example 49
Project: spring-boot-readiness   File: RestTemplateConfiguration.java   Source Code and License 5 votes vote down vote up
private HttpClientBuilder configure(HttpClientBuilder builder, String userAgent) {
    return builder
            .setUserAgent(userAgent)
            .disableAutomaticRetries()
            .setMaxConnTotal(settings.getServices().size())
            .setMaxConnPerRoute(settings.getServices().size());
}
 
Example 50
Project: java-bitbankcc   File: Bitbankcc.java   Source Code and License 5 votes vote down vote up
private <T extends Response> T doHttpPost(URIBuilder builder, Class<T> clazz, List<Header> header, StringEntity entityBody) throws BitbankException, IOException {
    try {
        URI uri = builder.build();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(entityBody);
        HttpClient client = HttpClientBuilder.create().setDefaultHeaders(header).build();
        return httpExecute(client, httpPost, clazz);
    } catch (URISyntaxException e) {
        throw new BitbankException(e.getMessage());
    }
}
 
Example 51
Project: aem-orchestrator   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
private CloseableHttpClient buildCloseableHttpClient() {

        CloseableHttpClient client;

        if (enableRelaxedSslHttpClient) {
            client = HttpClientBuilder.create()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();

        } else {
            client = HttpClientBuilder.create().build();
        }

        return client;
    }
 
Example 52
Project: spring-data-examples   File: RequiresSolrServer.java   Source Code and License 5 votes vote down vote up
private void checkServerRunning() {

		try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
			CloseableHttpResponse response = client.execute(new HttpGet(baseUrl + PING_PATH));
			if (response != null && response.getStatusLine() != null) {
				Assume.assumeThat(response.getStatusLine().getStatusCode(), Is.is(200));
			}
		} catch (IOException e) {
			throw new AssumptionViolatedException("SolrServer does not seem to be running", e);
		}
	}
 
Example 53
Project: Patterdale   File: PatterdaleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void readyPageReturns200andOK() throws Exception {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(new HttpGet("http://localhost:7001/ready"));

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    assertThat(responseBody(response)).contains("OK");
}
 
Example 54
Project: TradingRobot   File: Trading.java   Source Code and License 5 votes vote down vote up
private Trade getTrade() {
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpGet request = new HttpGet(RequestURI.baseURL+"/v3/accounts/"+RequestURI.accountId+"/openTrades");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		System.out.println(resultJson);
		try {
			 JSONObject trade = resultJson.getJSONArray("trades").getJSONObject(0);
			 //System.out.println(trade);
			 Trade t = new Trade();
			 t.setId(trade.getLong("id"));
			 t.setOpeningPrice(trade.getDouble("price"));
			 t.setBuyOrSell(trade.getString("currentUnits").contains("-") ? "sell" : "buy");
			 return t;
		}
		catch (JSONException je) {
			return null;
		}
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
	
}
 
Example 55
Project: spring-cloud-dashboard   File: HttpClientUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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.
 *
 * @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);
}
 
Example 56
Project: sunbird-lms-mw   File: BaseMetricsActor.java   Source Code and License 5 votes vote down vote up
public static String makePostRequest(String url, String body) throws Exception {
  ProjectLogger.log("Request to Ekstep for Metrics" + body);
  String baseSearchUrl = System.getenv(JsonKey.EKSTEP_BASE_URL);
  if (ProjectUtil.isStringNullOREmpty(baseSearchUrl)) {
    baseSearchUrl = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_BASE_URL);
  }
  String authKey = System.getenv(JsonKey.EKSTEP_AUTHORIZATION);
  if (ProjectUtil.isStringNullOREmpty(authKey)) {
    authKey = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_AUTHORIZATION);
  } else {
    authKey = JsonKey.BEARER + authKey;
  }
  HttpClient client = HttpClientBuilder.create().build();
  HttpPost post = new HttpPost(baseSearchUrl + PropertiesCache.getInstance().getProperty(url));
  post.addHeader("Content-Type", "application/json; charset=utf-8");
  post.addHeader(JsonKey.AUTHORIZATION, authKey);
  post.setEntity(new StringEntity(body, Charsets_UTF_8));
  HttpResponse response = client.execute(post);
  ProjectLogger.log("##ResponseCode" + response.getStatusLine().getStatusCode());
  if (response.getStatusLine().getStatusCode() != 200) {
    throw new ProjectCommonException(ResponseCode.unableToConnect.getErrorCode(),
        ResponseCode.unableToConnect.getErrorMessage(),
        ResponseCode.SERVER_ERROR.getResponseCode());
  }
  BufferedReader rd = new BufferedReader(
      new InputStreamReader(response.getEntity().getContent(), Charsets_UTF_8));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
    result.append(line);
  }
  ProjectLogger.log("Response from Ekstep for metrics"+ response.toString());
  return result.toString();
}
 
Example 57
Project: CityPower-Build-Sample   File: HttpClientConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public HttpClient httpClient() {
	log.debug("building httpClient");
	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

	// Get the poolMaxTotal value from our application[-?].yml or default to 10 if not explicitly set
	connectionManager.setMaxTotal(environment.getProperty("poolMaxTotal", Integer.class, 10));

	return HttpClientBuilder
			.create()
			.setConnectionManager(connectionManager)
			.build();
}
 
Example 58
Project: keti   File: UAAACSClientsUtil.java   Source Code and License 5 votes vote down vote up
private OAuth2RestTemplate getOAuth2RestTemplateForClient(final String tokenUrl, final String clientId,
        final String clientSecret) {
    ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    CloseableHttpClient httpClient = HttpClientBuilder.create().useSystemProperties().build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    restTemplate.setRequestFactory(requestFactory);

    return restTemplate;
}
 
Example 59
Project: logregator   File: HttpServerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testShouldBeCallHandleByHttpRequest() throws Exception {
    HttpClient http = HttpClientBuilder.create().build();
    http.execute(new HttpPost("http://localhost:9999/log"));

    verify(mockHttpHandler).handle(any(), any(), any());
}
 
Example 60
Project: integration-test-helper   File: AomHttpClient.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new AomHttpClient
 *
 * @param host "http://localhost:8080" for example
 * @param system the {@link AOMSystem} to use for further requests
 */
public AomHttpClient( String host, AOMSystem system )
{
	this.yambasHost = host == null ? System.getProperty( "yambasHost", "http://localhost:8080" ) : host;
	this.yambasBase = this.yambasHost + "/yambas/rest/";
	this.system = system;
	this.client = HttpClientBuilder.create( ).build( );
}