private HttpClient getClient() { if (client == null) { HttpClientBuilder clientBuilder = HttpClients.custom(); RequestConfig.Builder configBuilder = RequestConfig.custom(); if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { isUsingProxy = true; InetSocketAddress adr = (InetSocketAddress) proxy.address(); clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort())); } if (timeout != null) { configBuilder.setConnectTimeout(timeout.intValue()); } if (readTimeout != null) { configBuilder.setSocketTimeout(readTimeout.intValue()); } if (followRedirects != null) { configBuilder.setRedirectsEnabled(followRedirects.booleanValue()); } if (hostnameverifier != null) { SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier); clientBuilder.setSSLSocketFactory(sslConnectionFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory) .register("http", PlainConnectionSocketFactory.INSTANCE) .build(); clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } clientBuilder.setDefaultRequestConfig(configBuilder.build()); client = clientBuilder.build(); } return client; }
/** * Called primarily from HTTPMethod to do the bulk of the execution. Assumes HTTPMethod has * inserted its headers into request. * * @param method * @param methoduri * @param rb * @return Request+Response pair * @throws HTTPException */ ExecState execute(HTTPMethod method, URI methoduri, RequestBuilder rb) throws HTTPException { this.execution = new ExecState(); this.requestURI = methoduri; AuthScope methodscope = HTTPAuthUtil.uriToAuthScope(methoduri); AuthScope target = HTTPAuthUtil.authscopeUpgrade(this.scope, methodscope); synchronized (this) { // keep coverity happy // Merge Settings; Settings merged = HTTPUtil.merge(globalsettings, localsettings); if (!this.cachevalid) { RequestConfig.Builder rcb = RequestConfig.custom(); this.cachedconfig = configureRequest(rcb, merged); HttpClientBuilder cb = HttpClients.custom(); configClient(cb, merged); setAuthenticationAndProxy(cb); this.cachedclient = cb.build(); rb.setConfig(this.cachedconfig); this.cachevalid = true; } } this.execution.request = (HttpRequestBase) rb.build(); try { HttpHost targethost = HTTPAuthUtil.authscopeToHost(target); this.execution.response = cachedclient.execute(targethost, this.execution.request, this.sessioncontext); } catch (IOException ioe) { throw new HTTPException(ioe); } return this.execution; }
/** Executes the request against the appliance API (Should not be called directly). */ @Override public MuteCheckResponse executeRequest() throws MorpheusApiRequestException { CloseableHttpClient client = null; try { URIBuilder uriBuilder = new URIBuilder(endpointUrl); uriBuilder.setPath("/api/monitoring/checks/" + this.getCheckId() + "/quarantine"); HttpPut request = new HttpPut(uriBuilder.build()); this.applyHeaders(request); HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder.setDefaultRequestConfig(this.getRequestConfig()); client = clientBuilder.build(); request.addHeader("Content-Type", "application/json"); request.setEntity(new StringEntity(generateRequestBody())); CloseableHttpResponse response = client.execute(request); return MuteCheckResponse.createFromStream(response.getEntity().getContent()); } catch (Exception ex) { // Throw custom exception throw new MorpheusApiRequestException( "Error Performing API Request for muting/unmuting a Check", ex); } finally { if (client != null) { try { client.close(); } catch (IOException io) { // ignore } } } }
public static String shortIt(String longUrl) { if (!longUrl.startsWith("http")) { longUrl = "http://" + longUrl; } CloseableHttpClient httpclient = HttpClients.custom().build(); // 可以帮助记录cookie String result = longUrl; String uri = "http://vwz.me/API.php?url=" + longUrl + "&callback=json"; HttpGet get = new HttpGet(uri); try { CloseableHttpResponse execute = httpclient.execute(get); int statusCode = execute.getStatusLine().getStatusCode(); switch (statusCode) { case 200: String html = IOUtils.toString(execute.getEntity().getContent(), "UTF-8"); String json = html.substring(5, html.length() - 2); logger.info("json : {}", json); result = parseMsg(json); break; default: break; } } catch (IOException e) { e.printStackTrace(); } try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } logger.info("short {} to {}", longUrl, result); return result; }
private static CloseableHttpClient createHTTPClient( PrivateKey privateKey, X509Certificate certificate, boolean validateCertificate) { // HttpClientBuilder clientBuilder = HttpClientBuilder.create(); HttpClientBuilder clientBuilder = HttpClients.custom(); try { SSLContext sslContext = TrustUtils.getCustomSSLContext(privateKey, certificate, validateCertificate); clientBuilder.setSslcontext(sslContext); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | KeyManagementException | UnrecoverableKeyException | NoSuchProviderException ex) { LOGGER.log(Level.WARNING, "unable to set SSL context", ex); return null; } RequestConfig.Builder rcBuilder = RequestConfig.custom(); // handle redirects :) rcBuilder.setRedirectsEnabled(true); // HttpClient bug caused by Lighttpd rcBuilder.setExpectContinueEnabled(false); clientBuilder.setDefaultRequestConfig(rcBuilder.build()); // create connection manager // ClientConnectionManager connMgr = new SingleClientConnManager(params, registry); // return new DefaultHttpClient(connMgr, params); return clientBuilder.build(); }
/** * Tests that if a socket fails to connect, the allocated connection is properly released back to * the connection manager. */ @Test public void testSocketConnectFailureReleasesConnection() throws Exception { final HttpClientConnection conn = Mockito.mock(HttpClientConnection.class); final ConnectionRequest connrequest = Mockito.mock(ConnectionRequest.class); Mockito.when(connrequest.get(Mockito.anyInt(), Mockito.any(TimeUnit.class))).thenReturn(conn); final HttpClientConnectionManager connmgr = Mockito.mock(HttpClientConnectionManager.class); Mockito.doThrow(new ConnectException()) .when(connmgr) .connect( Mockito.any(HttpClientConnection.class), Mockito.any(HttpRoute.class), Mockito.anyInt(), Mockito.any(HttpContext.class)); Mockito.when(connmgr.requestConnection(Mockito.any(HttpRoute.class), Mockito.any())) .thenReturn(connrequest); final HttpClient client = HttpClients.custom().setConnectionManager(connmgr).build(); final HttpContext context = new BasicHttpContext(); final HttpGet httpget = new HttpGet("http://www.example.com/a"); try { client.execute(httpget, context); Assert.fail("expected IOException"); } catch (final IOException expected) { } Mockito.verify(connmgr).releaseConnection(conn, null, 0, TimeUnit.MILLISECONDS); }
private HttpClient createHttpClient() { if (Boolean.parseBoolean(System.getProperty("proxySet"))) { HttpHost httpHost = new HttpHost( System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort"))); DefaultProxyRoutePlanner defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(httpHost); return HttpClients.custom().setRoutePlanner(defaultProxyRoutePlanner).build(); // todo - need to support SOCKS protocol for this solution to work - jamesdbloom // 12/01/2014 // return HttpClients.custom().setRoutePlanner(new // SystemDefaultRoutePlanner(ProxySelector.getDefault())).build(); } else { return HttpClients.custom().build(); } }
@Test public void testTracingFalse() throws ClientProtocolException, IOException, UnsatisfiedExpectationException { when(clientTracer.startNewSpan(PATH)).thenReturn(null); final HttpRequestImpl request = new HttpRequestImpl(); request .method(Method.GET) .path(PATH) .httpMessageHeader(BraveHttpHeaders.Sampled.getName(), "false"); final HttpResponseImpl response = new HttpResponseImpl(200, null, null); responseProvider.set(request, response); final CloseableHttpClient httpclient = HttpClients.custom() .addInterceptorFirst(new BraveHttpRequestInterceptor(clientTracer)) .addInterceptorFirst(new BraveHttpResponseInterceptor(clientTracer)) .build(); try { final HttpGet httpGet = new HttpGet(REQUEST); final CloseableHttpResponse httpClientResponse = httpclient.execute(httpGet); assertEquals(200, httpClientResponse.getStatusLine().getStatusCode()); httpClientResponse.close(); mockServer.verify(); final InOrder inOrder = inOrder(clientTracer); inOrder.verify(clientTracer).startNewSpan(PATH); inOrder.verify(clientTracer).submitBinaryAnnotation("request", "GET " + PATH); inOrder.verify(clientTracer).setClientSent(); inOrder.verify(clientTracer).setClientReceived(); verifyNoMoreInteractions(clientTracer); } finally { httpclient.close(); } }
public static CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial( null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); }
private CloseableHttpClient generateClient(Site site) { HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager); if (site != null && site.getUserAgent() != null) { httpClientBuilder.setUserAgent(site.getUserAgent()); } else { httpClientBuilder.setUserAgent(""); } if (site == null || site.isUseGzip()) { httpClientBuilder.addInterceptorFirst( new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); } SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build(); httpClientBuilder.setDefaultSocketConfig(socketConfig); if (site != null) { httpClientBuilder.setRetryHandler( new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true)); } generateCookie(httpClientBuilder, site); return httpClientBuilder.build(); }
protected CloseableHttpClient newClient() { final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SOCKET_TIMEOUT.get()) .setConnectTimeout(CONNECTION_TIMEOUT.get()) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); return HttpClients.custom() .setConnectionManager(newConnectionManager()) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .setRedirectStrategy( new RedirectStrategy() { @Override public boolean isRedirected( HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return false; } @Override public HttpUriRequest getRedirect( HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return null; } }) .build(); }
public void afterPropertiesSet() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager()); if ((_login != null) && (_password != null)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl()); } else { if (_logger.isWarnEnabled()) { _logger.warn("Login and password are required"); } } try { setProxyHost(httpClientBuilder); _closeableHttpClient = httpClientBuilder.build(); if (_logger.isDebugEnabled()) { _logger.debug("Configured client for " + _protocol + "://" + _hostName); } } catch (Exception e) { _logger.error("Unable to configure client", e); } }
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials( new AuthScope( mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent("Android-Mms/2.0") .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); }
@RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST) public String formSubmit(@ModelAttribute User user, Model model) throws MalformedURLException, IOException { model.addAttribute("user", user); HttpPost post = new HttpPost( "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/"); BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName())); nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName())); nameValuePairs.add(new BasicNameValuePair("email", user.getEmail())); nameValuePairs.add(new BasicNameValuePair("password", user.getPassword())); nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation())); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(post); response = httpclient.execute(post); System.out.println("Status code is " + response.getStatusLine().getStatusCode()); System.out.println(response.toString()); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(response.getFirstHeader("Location")); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); EntityUtils.consume(response.getEntity()); /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html"); FileWriter fileWriter = new FileWriter(newTextFile); fileWriter.write(response.toString()); fileWriter.close();*/ return "result"; }
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try { HttpGet httpget = new HttpGet("https://localhost/protected"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
@Test public final void givenDeprecatedApi_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { instance = HttpClients.custom().build(); final HttpGet request = new HttpGet(SAMPLE_URL); request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0"); response = instance.execute(request); }
@Test public void example3() { CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookieStore.addCookie(cookie); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); }
private static HttpClient createHttpClient() { RequestConfig config = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build(); HttpClientBuilder hcBuilder = HttpClients.custom(); hcBuilder.setDefaultRequestConfig(config); return hcBuilder.build(); }
/** * Sets the timeouts of the HTTP client. * * @param connectionTimeout timeout until connection established in milliseconds. Zero means no * timeout. * @param socketTimeout timeout for waiting for data in milliseconds. Zero means no timeout. * @param maxRequests maximum number of connections to a particuar host */ public static void setParams(int connectionTimeout, int socketTimeout, int maxRequests) { PrudentHttpEntityResolver.maxRequests = maxRequests; PoolingHttpClientConnectionManager phcConnMgr; Registry<ConnectionSocketFactory> registry = // RegistryBuilder.<ConnectionSocketFactory>create() // .register("http", PlainConnectionSocketFactory.getSocketFactory()) // .register("https", SSLConnectionSocketFactory.getSocketFactory()) // .build(); HttpClientBuilder builder = HttpClients.custom(); builder.setRedirectStrategy(new LaxRedirectStrategy()); builder.setMaxConnPerRoute(maxRequests); builder.setMaxConnTotal(200); if ("true".equals(System.getProperty("nu.validator.xml.promiscuous-ssl", "false"))) { // try { SSLContext promiscuousSSLContext = new SSLContextBuilder() // .loadTrustMaterial( null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }) .build(); builder.setSslcontext(promiscuousSSLContext); HostnameVerifier verifier = // SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLConnectionSocketFactory promiscuousSSLConnSocketFactory = // new SSLConnectionSocketFactory(promiscuousSSLContext, verifier); registry = RegistryBuilder.<ConnectionSocketFactory>create() // .register("https", promiscuousSSLConnSocketFactory) // .register("http", PlainConnectionSocketFactory.getSocketFactory()) // .build(); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | NumberFormatException e) { e.printStackTrace(); } } phcConnMgr = new PoolingHttpClientConnectionManager(registry); phcConnMgr.setDefaultMaxPerRoute(maxRequests); phcConnMgr.setMaxTotal(200); builder.setConnectionManager(phcConnMgr); RequestConfig.Builder config = RequestConfig.custom(); config.setCircularRedirectsAllowed(true); config.setMaxRedirects(20); // Gecko default config.setConnectTimeout(connectionTimeout); config.setCookieSpec(CookieSpecs.BEST_MATCH); config.setSocketTimeout(socketTimeout); client = builder.setDefaultRequestConfig(config.build()).build(); }
public static String wechatPost(String url, String params, InputStream keyStream) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try { keyStore.load(keyStream, WeixinConfig.MCH_ID.toCharArray()); } finally { keyStream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WeixinConfig.MCH_ID.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { String resp = ""; HttpPost httpPost = new HttpPost(url); StringEntity ent = new StringEntity(params, "utf-8"); ent.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(ent); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { resp += text; } } EntityUtils.consume(entity); return resp; } catch (Exception e) { } finally { response.close(); } } finally { httpclient.close(); } return null; }
@Test public void example2() { RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build(); RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.DEFAULT).build(); HttpGet httpGet = new HttpGet("http://baidu.com"); httpGet.setConfig(localConfig); }
// 获得设置代理的httpClent实例 private CloseableHttpClient getHttpClientWithProxy(HttpProxy proxy) { HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(proxy.getHost(), proxy.getPort()), new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword())); return HttpClients.custom() .setProxy(proxyHost) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
public static HttpClient createUnsafeClient() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; } catch (Exception e) { throw new RuntimeException(e); } }
@Before public void init() throws Exception { httpServer = new HttpAPIServer(holder).start(); httpServerUrl = String.format("http://localhost:%s/", httpPort); // this http client doesn't close HTTP connection. httpclient = HttpClients.custom() .setConnectionReuseStrategy((response, context) -> true) .setKeepAliveStrategy((response, context) -> 10000000) .build(); }
static { HttpClientBuilder custom = HttpClients.custom(); custom.setUserAgent("Mozilla/5.0 (Windows NT 6.1; rv:25.0) Gecko/20100101 Firefox/25.0"); RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(5 * 1000) .setSocketTimeout(30 * 1000) .setConnectTimeout(5 * 1000) .build(); custom.setDefaultRequestConfig(config); httpclient = custom.build(); minHttpclient = HttpClients.createMinimal(); }
/** * Return a http client instance * * @param protocol- service endpoint protocol http/https * @return */ public static HttpClient getHttpClient(int port, String protocol) throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClient httpclient; if (HTTPS_PROTOCOL.equals(protocol)) { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { httpclient = HttpClients.createDefault(); } return httpclient; }
/** Gets an http client to perform requests. */ public CloseableHttpClient getHttpClient() { CloseableHttpClient result; try { final SSLContextBuilder builder = new SSLContextBuilder(); if (trustAllMode) builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()) { /* This is patched to avoid "Could not generate DH keypair" error with JDK < 1.8 */ protected void prepareSocket(SSLSocket socket) throws IOException { final String[] enabledCipherSuites = socket.getEnabledCipherSuites(); final String version = System.getProperty("java.version"); final List<String> list = new ArrayList<String>(Arrays.asList(enabledCipherSuites)); if (!version.startsWith("1.8")) { list.remove("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"); list.remove("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA"); list.remove("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"); } socket.setEnabledCipherSuites(list.toArray(new String[list.size()])); } }; result = HttpClients.custom() .setSSLSocketFactory(sslsf) .setRedirectStrategy(new LaxRedirectStrategy()) .useSystemProperties() .build(); } catch (Exception e) { LOG.warning("Could not create custom http client, using default: " + e.getMessage()); result = HttpClients.custom() .setRedirectStrategy(new LaxRedirectStrategy()) .useSystemProperties() .build(); } return result; }
@Override public CloseableHttpClient createClient() { SSLConnectionSocketFactory sslsf = buildSSLSocket(); RequestConfig requestConfig = buildConfig(); httpClient = HttpClients.custom() .setSSLSocketFactory(sslsf) .setDefaultRequestConfig(requestConfig) .build(); return httpClient; }
protected final void testBasicSslWithKeyStore(String keyStore) throws Exception { AbstractEmbeddedServletContainerFactory factory = getFactory(); addTestTxtFile(factory); factory.setSsl(getSsl(null, "password", keyStore)); this.container = factory.getEmbeddedServletContainer(); this.container.start(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory), equalTo("test")); }
public static CloseableHttpClient buildHttpClient() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {} } }; SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, trustAllCerts, new java.security.SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; }