List of usage examples for org.apache.http.impl.client HttpClients custom
public static HttpClientBuilder custom()
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession createSession(final String username, String password) throws ScratchLoginException { try {// w w w. j a va 2 s .c o m final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); resp = httpClient.execute(csrf); resp.close(); String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); final JSONObject loginObj = new JSONObject(); loginObj.put("username", username); loginObj.put("password", password); loginObj.put("captcha_challenge", ""); loginObj.put("captcha_response", ""); loginObj.put("embed_captcha", false); loginObj.put("timezone", "America/New_York"); loginObj.put("csrfmiddlewaretoken", csrfToken); final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build(); resp = httpClient.execute(login); password = null; final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject( result.toString().substring(1, result.toString().length() - 1)); if ((int) jsonOBJ.get("success") != 1) throw new ScratchLoginException(); String ssi = null; String sct = null; String e = null; final Header[] headers = resp.getAllHeaders(); for (final Header header : headers) if (header.getName().equals("Set-Cookie")) { final String value = header.getValue(); final String[] split = value.split(Pattern.quote("; ")); for (final String s : split) { if (s.contains("=")) { final String[] split2 = s.split(Pattern.quote("=")); final String key = split2[0]; final String val = split2[1]; if (key.equals("scratchsessionsid")) ssi = val; else if (key.equals("scratchcsrftoken")) sct = val; else if (key.equals("expires")) e = val; } } } resp.close(); return new ScratchSession(ssi, sct, e, username); } catch (final IOException e) { e.printStackTrace(); throw new ScratchLoginException(); } }
From source file:info.bonjean.beluga.connection.BelugaHTTPClient.java
private BelugaHTTPClient() { BelugaConfiguration configuration = BelugaConfiguration.getInstance(); HttpClientBuilder clientBuilder = HttpClients.custom(); // timeout// w w w.jav a 2s . c om RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT) .setConnectionRequestTimeout(TIMEOUT).build(); clientBuilder.setDefaultRequestConfig(config); switch (configuration.getConnectionType()) { case PROXY_DNS: Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()).build(); BelugaDNSResolver dnsOverrider = new BelugaDNSResolver(DNSProxy.PROXY_DNS); connectionManager = new PoolingHttpClientConnectionManager(registry, dnsOverrider); break; case HTTP_PROXY: HttpHost proxy = new HttpHost(configuration.getProxyHost(), configuration.getProxyPort(), "http"); clientBuilder.setProxy(proxy); break; default: } // limit the pool size connectionManager.setDefaultMaxPerRoute(2); // add interceptor, currently for debugging only clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { HttpInetConnection connection = (HttpInetConnection) context .getAttribute(HttpCoreContext.HTTP_CONNECTION); log.debug("Remote address: " + connection.getRemoteAddress()); // TODO: reimplement blacklisting for DNS proxy by maintaining a // map [DNS IP,RESOLVED IP] in the DNS resolver for reverse // lookup } }); // finally create the HTTP client clientBuilder.setConnectionManager(connectionManager); httpClient = clientBuilder.build(); }
From source file:retsys.client.http.HttpHelper.java
public HttpClient getHttpClient(CredentialsProvider credsProvider) { HttpClient client = null;/*from ww w . java2s . com*/ if (credsProvider == null) { client = HttpClients.createDefault(); } else { client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } return client; }
From source file:com.github.vanroy.cloud.dashboard.config.CloudDashboardConfig.java
@Bean public HttpClient HttpClient() { return HttpClients.custom().setMaxConnTotal(100) .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(2000).build()) .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(1000) .setConnectionRequestTimeout(1000).build()) .build();// www . j av a 2s . com }
From source file:com.microsoft.azure.hdinsight.common.task.MultiRestTask.java
@Override public List<String> call() throws Exception { CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider) .build();/*from w ww.j a v a2s. c o m*/ List<String> results = new ArrayList<>(); for (String path : paths) { HttpGet httpGet = new HttpGet(path); httpGet.addHeader("Content-Type", "application/json"); CloseableHttpResponse response = httpclient.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (code == 200 || code == 201) { results.add(EntityUtils.toString(response.getEntity())); } else { throw new HDIException(response.getStatusLine().getReasonPhrase(), code); } } return results; }
From source file:sft.LoginAndBookSFT.java
public void startBooking() throws URISyntaxException, MalformedURLException, ProtocolException, IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); try {//from ww w . j a v a 2 s . co m // get cookie final HttpGet httpget = new HttpGet("https://sft.ticketack.com"); final CloseableHttpResponse response1 = httpclient.execute(httpget); try { final HttpEntity entity = response1.getEntity(); System.out.println("Login form get: " + response1.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); final List<Cookie> _cookies = cookieStore.getCookies(); if (_cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < _cookies.size(); i++) { System.out.println("- " + _cookies.get(i).toString()); } } } finally { response1.close(); } // login final HttpUriRequest login = RequestBuilder.post() .setUri(new URI("https://sft.ticketack.com/ticket/view/")) .addParameter("ticket_number", username).addParameter("ticket_key", password).build(); final CloseableHttpResponse response2 = httpclient.execute(login); try { final HttpEntity entity = response2.getEntity(); System.out.println("Login form get: " + response2.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); final List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { // System.out.println("- " + cookies.get(i).toString()); } } } finally { response2.close(); } } finally { httpclient.close(); } final Cookie _cookie = cookieStore.getCookies().get(0); final String mightyCooke = "PHPSESSID=" + _cookie.getValue(); for (final String _booking : bookings) { // get free seatings // json https://sft.ticketack.com/screening/infos_json/02c101f9-c62a-445e-ad72-19fb32db34c0 final String _json = doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/infos_json/"); final Gson gson = new Gson(); final Example _allInfos = gson.fromJson(_json, Example.class); if (_allInfos.getCinemaHall().getMap() != null) { final String _mySeat = getMeAFreeSeat(_json); // book on seating // 02c101f9-c62a-445e-ad72-19fb32db34c0?format=json&overbook=false&seat=Parkett%20Rechts:1:16 try { if (_mySeat != null) doGet(mightyCooke, _booking + "?format=json&overbook=true&seat=" + URLEncoder.encode(_mySeat, "UTF-8"), "https://sft.ticketack.com/screening/book_on_ticket/"); } catch (final MalformedURLException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final ProtocolException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final UnsupportedEncodingException exception) { System.err.println("Error: " + exception.getMessage()); } catch (final IOException exception) { System.err.println("Error: " + exception.getMessage()); } System.out.println("booking (seat) done for: " + _booking); } else { // book // https://sft.ticketack.com/screening/book_on_ticket/76c039cc-d1d5-40a1-9a5d-2b1cd4c47799 // Cookie:PHPSESSID=s1a6a8casfhidfq68tqn2cb565 doGet(mightyCooke, _booking, "https://sft.ticketack.com/screening/book_on_ticket/"); System.out.println("booking done for: " + _booking); } } System.out.println("All done!"); }
From source file:io.openvidu.test.e2e.utils.CustomHttpClient.java
public CustomHttpClient(String openviduUrl, String openviduSecret) { this.openviduUrl = openviduUrl.replaceFirst("/*$", ""); this.headerAuth = "Basic " + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + openviduSecret).getBytes()); SSLContext sslContext = null; try {/*from w ww . j a v a 2s . com*/ sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { Assert.fail("Error building custom HttpClient: " + e.getMessage()); } HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); Unirest.setHttpClient(unsafeHttpClient); }
From source file:de.fraunhofer.iosb.ilt.stc.auth.AuthBasic.java
@Override public void setAuth(SensorThingsService service) { try {/*from w w w. j a v a 2s . c om*/ CredentialsProvider credsProvider = new BasicCredentialsProvider(); URL url = service.getEndpoint().toURL(); credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue())); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); service.setClient(httpclient); } catch (MalformedURLException ex) { LOGGER.error("Failed to initialise basic auth.", ex); } }
From source file:com.microsoft.azure.hdinsight.common.task.LivyTask.java
@Override public String call() throws Exception { CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider) .build();/*from w w w . j a v a 2 s . c o m*/ HttpGet httpGet = new HttpGet(path); httpGet.addHeader("Content-Type", "application/json"); CloseableHttpResponse response = httpclient.execute(httpGet); int code = response.getStatusLine().getStatusCode(); HttpEntity httpEntity = response.getEntity(); return IOUtils.toString(httpEntity.getContent(), Charset.forName("utf-8")); }
From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java
@Override public DalCloseableHttpClient createCloseableHttpClient(SSLContext context) { HttpClientBuilder builder = HttpClients.custom(); builder.setSslcontext(context);/* ww w .j a va 2 s. c o m*/ return new DalCloseableHttpClientImpl(builder.build()); }