List of usage examples for org.apache.http.impl.client HttpClientBuilder create
public static HttpClientBuilder create()
From source file:org.apache.samza.autoscaling.utils.YarnUtil.java
public YarnUtil(String rmAddress, int rmPort) { this.httpClient = HttpClientBuilder.create().build(); this.rmServer = new HttpHost(rmAddress, rmPort, "http"); log.info("setting rm server to : " + rmServer); YarnConfiguration hConfig = new YarnConfiguration(); hConfig.set(YarnConfiguration.RM_ADDRESS, rmAddress + ":" + YarnConfiguration.DEFAULT_RM_PORT); yarnClient = YarnClient.createYarnClient(); yarnClient.init(hConfig);/* www . j a va 2s. c o m*/ yarnClient.start(); }
From source file:juzu.impl.plugin.amd.AmdMaxAgeTestCase.java
@Test @RunAsClient//from w ww .j a v a2s .c om public void test() throws Exception { URL applicationURL = applicationURL(); driver.get(applicationURL.toString()); WebElement elt = driver.findElement(By.id("Foo")); URL url = new URL(applicationURL.getProtocol(), applicationURL.getHost(), applicationURL.getPort(), elt.getText()); HttpGet get = new HttpGet(url.toURI()); HttpResponse response = HttpClientBuilder.create().build().execute(get); Header[] cacheControl = response.getHeaders("Cache-Control"); assertEquals(1, cacheControl.length); assertEquals("max-age=1000", cacheControl[0].getValue()); }
From source file:eu.over9000.skadi.service.DownloadService.java
public DownloadService(String remoteUrl, File localFile) { this.httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(new DefaultHostnameVerifier()).build(); this.remoteUrl = remoteUrl; this.localFile = localFile; }
From source file:com.meli.client.controller.AppController.java
private static void doApiCalls(String query, String countryCode) { List<Item> items = new ArrayList<Item>(); Random r = new Random(); Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq"); try {// ww w . j a v a2 s. c om FluentStringsMap params = new FluentStringsMap(); params.add("q", query); String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search"; Response response = meliOb.get(path, params); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(response.getResponseBody()); JsonNode resultNode = rootNode.findPath("results"); if (resultNode.size() > 0) { JsonNode currNode = null; JsonNode dupNode = null; boolean dupNodeVal = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); Item item = null; int randomMins; String checkDupsUrl = null; HttpGet get = null; URIBuilder builder = null; URI uri = null; for (int i = 0; i < resultNode.size(); i++) { currNode = resultNode.get(i); builder = new URIBuilder(); builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check") .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText()); uri = builder.build(); get = new HttpGet(uri); get.addHeader("accept", "application/json"); CloseableHttpResponse res = httpClient.execute(get); BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String content = "", line; while ((line = br.readLine()) != null) { content = content + line; } if (!content.isEmpty()) { dupNode = objectMapper.readTree(content); dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText()); if (dupNodeVal && !allowDuplicates) continue; item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? currNode.get("site_id").asText(), currNode.get("title").asText(), currNode.get("permalink").asText(), currNode.get("category_id").asText(), currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText() "", //currNode.get("seller").get("link").asText() "", //currNode.get("seller").get("email").asText() currNode.get("price").asText(), "", //currNode.get("auction_price").asText(), "", //currNode.get("currency_id").asText(), currNode.get("thumbnail").asText()); items.add(item); } randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime; Thread.sleep(randomMins); } if (!items.isEmpty()) { HttpPost post = new HttpPost(apiUrl + "/proxy/add"); StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items)); post.setEntity(stringEntity); post.setHeader("Content-type", "application/json"); CloseableHttpResponse postResponse = httpClient.execute(post); System.out.println("this is the reponse of the final request: " + postResponse.getStatusLine().getStatusCode()); } } } catch (MeliException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.squid.kraken.v4.auth.RequestHelper.java
public static <T> T processRequest(Class<T> type, HttpServletRequest request, HttpRequestBase req) throws IOException, URISyntaxException, ServerUnavailableException, ServiceException, SSORedirectException {/*from w w w. j a v a2 s .c om*/ // set client information to the header String reqXFF = request.getHeader(STRING_XFF_HEADER); String postXFF; if (reqXFF != null) { // X-Forwarded-For header already exists in the request logger.info(STRING_XFF_HEADER + " : " + reqXFF); if (reqXFF.length() > 0) { // just add the remoteHost to it postXFF = reqXFF + ", " + request.getRemoteHost(); } else { postXFF = request.getRemoteHost(); } } else { postXFF = request.getRemoteHost(); } // add a new X-Forwarded-For header containing the remoteHost req.addHeader(STRING_XFF_HEADER, postXFF); // execute the login request HttpResponse executeCode; try { HttpClient client = HttpClientBuilder.create().build(); executeCode = client.execute(req); } catch (ConnectException e) { // Authentication server unavailable throw new ServerUnavailableException(e); } // process the result BufferedReader rd = new BufferedReader(new InputStreamReader(executeCode.getEntity().getContent())); StringBuffer resultBuffer = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { resultBuffer.append(line); } String result = resultBuffer.toString(); T fromJson; Gson gson = new Gson(); int statusCode = executeCode.getStatusLine().getStatusCode(); if (statusCode != 200) { if (executeCode.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String redirectURL = executeCode.getFirstHeader("Location").getValue(); throw new SSORedirectException("SSO Redirect Exception", redirectURL); } else { logger.info("Error : " + req.getURI() + " resulted in : " + result); WebServicesException exception; try { exception = gson.fromJson(result, WebServicesException.class); } catch (Exception e) { if ((statusCode >= 500) && (statusCode < 600)) { // Authentication server unavailable throw new ServerUnavailableException(); } else { throw new ServiceException(); } } throw new ServiceException(exception); } } else { // forward to input page displaying ok message try { fromJson = gson.fromJson(result, type); } catch (Exception e) { throw new ServiceException(e); } } return fromJson; }
From source file:org.n52.instagram.dao.AbstractRemoteDAO.java
protected Map<?, ?> executeApiRequest(String target) { HttpGet get = new HttpGet(target); try (CloseableHttpClient client = HttpClientBuilder.create().build();) { CloseableHttpResponse response = client.execute(get); if (response.getEntity() != null) { Map<?, ?> json = JsonUtil.createJson(response.getEntity().getContent()); return json; } else {// w ww .j av a2 s . c om logger.warn("Could not retrieve contents. No entity."); } } catch (IOException e) { logger.warn("Could not retrieve contents of " + get.getURI(), e); } return null; }
From source file:org.commonjava.indy.rest.apigen.SwaggerExportTest.java
@Test public void downloadApiFiles() { CloseableHttpClient client = HttpClientBuilder.create().build(); Arrays.asList("yaml", "json").forEach(ext -> { HttpGet get = new HttpGet( UrlUtils.buildUrl("http://localhost:" + fixture.getBootOptions().getPort(), "swagger." + ext)); get.setHeader(ApplicationHeader.accept.key(), "application/" + ext); try (CloseableHttpResponse response = client.execute(get)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); String content = IOUtils.toString(response.getEntity().getContent()); FileUtils.write(new File("target/classes/indy-rest-api." + ext), content); } catch (IOException e) { e.printStackTrace();//from ww w .j a v a2 s . c om fail("failed to retrieve swagger." + ext); } }); }
From source file:services.SecurityService.java
public void otpv2(String otp) throws IOException, JSONException { CloseableHttpClient client = HttpClientBuilder.create().build(); JSONObject obj = new JSONObject(); JSONObject msgObject = new JSONObject(); msgObject.put("body", otp); msgObject.put("title", "notification"); obj.put("to", "etN09hk7SII:APA91bGSE-G6jEKywU6D368rNRrd77zgL2UmKglsDhs-mdOsSJB4zrSS450D6TrrnwGiANx8wrn1mRCxYoJE_Qr743PVLCeN-mzL36UCQFYXMyqBJMQZr9nFKrvW7HmAQ5_507CUK7ys"); obj.put("notification", msgObject); StringEntity requestEntity = new StringEntity(obj.toString(), ContentType.APPLICATION_JSON); HttpPost postMethod = new HttpPost(ANDROID_NOTIFICATION_URL); postMethod.setHeader("Content-type", "application/json"); postMethod.setHeader("Authorization", "key=" + ANDROID_NOTIFICATION_KEY); postMethod.setEntity(requestEntity); HttpResponse rawResponse = client.execute(postMethod); }
From source file:org.wso2.security.tools.product.manager.NotificationManager.java
private static void notifyStatus(String path, boolean status) throws NotificationManagerException { int i = 0;/*from w w w . j a v a 2 s . c o m*/ while (i < 10) { try { URI uri = (new URIBuilder()).setHost(automationManagerHost).setPort(automationManagerPort) .setScheme("http").setPath(path).addParameter("containerId", myContainerId) .addParameter("status", String.valueOf(status)).build(); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(uri); HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LOGGER.info("Notified successfully"); return; } else { i++; } Thread.sleep(2000); } catch (URISyntaxException | InterruptedException | IOException e) { e.printStackTrace(); LOGGER.error(e.toString()); i++; } } throw new NotificationManagerException("Error occurred while notifying status to Automation Manager"); }