List of usage examples for org.apache.http.impl.client HttpClients custom
public static HttpClientBuilder custom()
From source file:com.law.commons.util.MyHttpWrapper.java
/** * Apply post http request to the back server. * * @return boolean success/fail/*from w ww . j a v a2 s . com*/ */ protected boolean doPost() { boolean ret = false; try { BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore) .setDefaultHeaders(this.headers).build(); HttpEntity entity = new UrlEncodedFormEntity(this.params, "UTF-8"); HttpPost request = new HttpPost(this.websrvurl); request.setEntity(entity); // logger.info("???:"+DateUtil.getNowOfNODIV()); CloseableHttpResponse response = httpclient.execute(request); // logger.info("???:"+DateUtil.getNowOfNODIV()); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity rentity = response.getEntity(); String sEntity = EntityUtils.toString(rentity); // parse json here. JSONObject jsonObject = JSONObject.fromObject(sEntity); String res = jsonObject.getString("response").trim(); if (res.equals("OK")) { ret = true; } } } catch (Exception ex) { logger.error(ex); } finally { } return ret; }
From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImplTest.java
@Before public void setup() throws Exception { config = new HashMap<String, Object>(); username = RandomStringUtils.randomAlphabetic(5); password = RandomStringUtils.randomAlphabetic(6); final String authHeaderValue = Base64.encodeBase64String((username + ":" + password).getBytes()); config.put("hostname", "localhost"); config.put("port", mockServerRule.getPort().intValue()); mockServerClient.when(request().withMethod("GET").withPath("/anon")) .respond(response().withStatusCode(200).withBody("OK")); mockServerClient.when(request().withMethod("GET").withPath("/anonJson")) .respond(response().withStatusCode(200).withBody("{ 'foo' : 'bar' }")); mockServerClient.when(request().withMethod("GET").withPath("/auth").withHeader("Authorization", "Basic " + authHeaderValue)).respond(response().withStatusCode(200).withBody("OK")); impl = new HttpClientFactoryImpl(); PrivateAccessor.setField(impl, "httpClientBuilderFactory", new HttpClientBuilderFactory() { @Override// www . jav a2s. c om public HttpClientBuilder newBuilder() { return HttpClients.custom(); } }); }
From source file:org.elasticsearch.http.netty.NettyHttpCompressionIT.java
public void testUncompressedResponseByDefault() throws Exception { ensureGreen();/*w ww. java 2 s. c om*/ ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor(); CloseableHttpClient internalClient = HttpClients.custom().disableContentCompression() .addInterceptorFirst(headerExtractor).build(); HttpResponse response = httpClient(internalClient).path("/").execute(); assertEquals(200, response.getStatusCode()); assertFalse(headerExtractor.hasContentEncodingHeader()); }
From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java
/** * Default constructor./*from w w w.ja va 2 s .com*/ * * @param host Hostname of the Neo4j instance. * @param port HTTP port of the Neo4j instance. * @param secure If the connection used SSL. * @param properties Properties of the url connection. */ public CypherExecutor(String host, Integer port, Boolean secure, Properties properties) throws SQLException { this.secure = secure; // Create the http client builder HttpClientBuilder builder = HttpClients.custom(); // Adding authentication to the http client if needed CredentialsProvider credentialsProvider = getCredentialsProvider(host, port, properties); if (credentialsProvider != null) builder.setDefaultCredentialsProvider(credentialsProvider); // Setting user-agent String userAgent = properties.getProperty("useragent"); builder.setUserAgent("Neo4j JDBC Driver" + (userAgent != null ? " via " + userAgent : "")); // Create the http client this.http = builder.build(); // Create the url endpoint this.transactionUrl = createTransactionUrl(host, port, secure); // Setting autocommit this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true"))); }
From source file:org.apache.stratos.metadata.client.rest.DefaultRestClient.java
public DefaultRestClient(String username, String password) throws RestClientException { this.username = username; this.password = password; SSLContextBuilder builder = new SSLContextBuilder(); SSLConnectionSocketFactory sslConnectionFactory; try {// w w w.j a v a 2 s .co m builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslConnectionFactory = new SSLConnectionSocketFactory(builder.build()); } catch (NoSuchAlgorithmException e) { throw new RestClientException(e); } catch (KeyManagementException e) { throw new RestClientException(e); } catch (KeyStoreException e) { throw new RestClientException(e); } CloseableHttpClient closableHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionFactory) .setConnectionManager(HTTPConnectionManager.getInstance().getHttpConnectionManager()).build(); this.httpClient = closableHttpClient; }
From source file:org.zalando.stups.tokens.CloseableHttpProvider.java
public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials, URI accessTokenUri, HttpConfig httpConfig) { this.userCredentials = userCredentials; this.accessTokenUri = accessTokenUri; requestConfig = RequestConfig.custom().setSocketTimeout(httpConfig.getSocketTimeout()) .setConnectTimeout(httpConfig.getConnectTimeout()) .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout()) .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled()).build(); // prepare basic auth credentials final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()), new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret())); client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build(); host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme()); // enable basic auth for the request final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth);// w w w . j a v a 2s . c o m localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); }
From source file:com.microsoft.azure.hdinsight.spark.common.SparkInteractiveSessions.java
/** * get all sessions/*from w ww. j a va2 s. c om*/ * * @param connectUrl : eg http://localhost:8998/sessions * @return response result * @throws IOException */ public HttpResponse getAllSessions(String connectUrl) throws IOException { CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider) .build(); HttpGet httpGet = new HttpGet(connectUrl); httpGet.addHeader("Content-Type", "application/json"); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { return StreamUtil.getResultFromHttpResponse(response); } }
From source file:org.mule.test.integration.security.HttpListenerAuthenticationTestCase.java
private void getHttpResponse(CredentialsProvider credsProvider) throws IOException { HttpPost httpPost = new HttpPost(String.format("http://localhost:%s/basic", listenPort.getNumber())); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); httpResponse = httpClient.execute(httpPost); }
From source file:com.meltmedia.cadmium.core.github.ApiClient.java
protected static HttpClient createStaticHttpClient() { HttpClient client = HttpClients.custom() .setDefaultSocketConfig(SocketConfig.custom().setSoReuseAddress(true).build()).build(); return client; }