List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:com.srotya.tau.alerts.media.HttpService.java
/** * @param destination/*w w w . ja v a 2 s .co m*/ * @param bodyContent * @throws AlertDeliveryException */ public void sendHttpCallback(String destination, String bodyContent) throws AlertDeliveryException { try { CloseableHttpClient client = Utils.buildClient(destination, 3000, 3000); HttpPost request = new HttpPost(destination); StringEntity body = new StringEntity(bodyContent, ContentType.APPLICATION_JSON); request.addHeader("content-type", "application/json"); request.setEntity(body); HttpResponse response = client.execute(request); EntityUtils.consume(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 && statusCode >= 300) { throw exception; } client.close(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException | AlertDeliveryException e) { throw exception; } }
From source file:com.foundationdb.server.service.security.RestSecurityIT.java
private int openRestURL(String request, String query, String userInfo, boolean post) throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpRequestBase httpRequest;/*from w ww .j a v a 2s. c o m*/ if (post) { httpRequest = new HttpPost(getRestURL(request, "", userInfo)); ((HttpPost) httpRequest).setEntity(new ByteArrayEntity(query.getBytes("UTF-8"))); } else { httpRequest = new HttpGet(getRestURL(request, query, userInfo)); } HttpResponse response = client.execute(httpRequest); int code = response.getStatusLine().getStatusCode(); EntityUtils.consume(response.getEntity()); client.close(); return code; }
From source file:org.jboss.additional.testsuite.jdkall.present.ejb.sfsb.SfsbTestCase.java
@Test @OperateOnDeployment(DEPLOYMENT)// w w w . ja v a 2s. c om public void sfsbTest(@ArquillianResource URL url) throws Exception { URL testURL = new URL(url.toString() + "sfsbCache?product=makaronia&quantity=10"); final HttpGet request = new HttpGet(testURL.toString()); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { response = httpClient.execute(request); Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode()); Thread.sleep(1000); response = httpClient.execute(request); Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK, response.getStatusLine().getStatusCode()); } finally { IOUtils.closeQuietly(response); httpClient.close(); } }
From source file:org.flowable.app.service.idm.RemoteIdmServiceImpl.java
protected JsonNode callRemoteIdmService(String url, String username, String password) { HttpGet httpGet = new HttpGet(url); httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("UTF-8"))))); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); SSLConnectionSocketFactory sslsf = null; try {//from w w w .j a v a 2 s. c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientBuilder.setSSLSocketFactory(sslsf); } catch (Exception e) { logger.warn("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return objectMapper.readTree(response.getEntity().getContent()); } } catch (Exception e) { logger.warn("Exception while getting token", e); } finally { if (client != null) { try { client.close(); } catch (IOException e) { logger.warn("Exception while closing http client", e); } } } return null; }
From source file:com.enioka.jqm.tools.JettyTest.java
@Test public void testSslClientCert() throws Exception { Helpers.setSingleParam("enableWsApiSsl", "true", em); Helpers.setSingleParam("disableWsApi", "false", em); Helpers.setSingleParam("enableWsApiAuth", "false", em); addAndStartEngine();/*from w w w . j av a2 s. c om*/ // Launch a job so as to be able to query its status later CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar", TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true, em); JobRequest j = new JobRequest("MarsuApplication", "TestUser"); int i = JqmClientFactory.getClient().enqueue(j); TestHelpers.waitFor(1, 10000, em); // Server auth against trusted CA root certificate KeyStore trustStore = KeyStore.getInstance("JKS"); FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks")); try { trustStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } // Client auth JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert", "./conf/client.cer"); KeyStore clientStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File("./conf/client.pfx")); try { clientStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build(); int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class) .setParameter("i", TestHelpers.node.getId()).getSingleResult(); HttpUriRequest rq = new HttpGet( "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i); CloseableHttpResponse rs = cl.execute(rq); Assert.assertEquals(200, rs.getStatusLine().getStatusCode()); rs.close(); cl.close(); }
From source file:com.srotya.tau.alerts.media.HttpService.java
/** * @param alert//w w w .j av a 2 s . c o m * @throws AlertDeliveryException */ public void sendHttpCallback(Alert alert) throws AlertDeliveryException { try { CloseableHttpClient client = Utils.buildClient(alert.getTarget(), 3000, 3000); HttpPost request = new HttpPost(alert.getTarget()); StringEntity body = new StringEntity(alert.getBody(), ContentType.APPLICATION_JSON); request.addHeader("content-type", "application/json"); request.setEntity(body); HttpResponse response = client.execute(request); EntityUtils.consume(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 && statusCode >= 300) { throw exception; } client.close(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException | AlertDeliveryException e) { throw exception; } }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public IMediaFileWrapper doDownload(String url) throws Exception { CloseableHttpClient _httpClient = HttpClientHelper.create() .setConnectionTimeout(new Long(DateTimeUtils.MINUTE * 5).intValue()).__doBuildHttpClient(); try {/*from w ww. java 2 s . c o m*/ return _httpClient.execute(RequestBuilder.get().setUri(url).build(), __INNER_DOWNLOAD_HANDLER); } finally { _httpClient.close(); } }
From source file:com.glaf.core.util.http.HttpClientUtils.java
/** * ??GET/*w ww. j av a2 s . c om*/ * * @param url * ?? * @param encoding * * @param dataMap * ? * * @return */ public static String doGet(String url, String encoding, Map<String, String> dataMap) { StringBuffer buffer = new StringBuffer(); HttpGet httpGet = null; InputStreamReader is = null; BufferedReader reader = null; BasicCookieStore cookieStore = new BasicCookieStore(); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build(); try { if (dataMap != null && !dataMap.isEmpty()) { StringBuffer sb = new StringBuffer(); for (Map.Entry<String, String> entry : dataMap.entrySet()) { String name = entry.getKey().toString(); String value = entry.getValue(); sb.append("&").append(name).append("=").append(value); } if (StringUtils.contains(url, "?")) { url = url + sb.toString(); } else { url = url + "?xxxx=1" + sb.toString(); } } httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); is = new InputStreamReader(entity.getContent(), encoding); reader = new BufferedReader(is); String tmp = reader.readLine(); while (tmp != null) { buffer.append(tmp); tmp = reader.readLine(); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { IOUtils.closeStream(reader); IOUtils.closeStream(is); if (httpGet != null) { httpGet.releaseConnection(); } try { client.close(); } catch (IOException ex) { } } return buffer.toString(); }
From source file:org.docx4j.services.client.ConverterHttp.java
/** * Convert InputStream fromFormat to toFormat, streaming result to OutputStream os. * //from w w w . j av a 2s . co m * fromFormat supported: DOC, DOCX * * toFormat supported: PDF * * Note this uses a non-repeatable request entity, so it may not be suitable * (depending on the endpoint config). * * @param instream * @param fromFormat * @param toFormat * @param os * @throws IOException * @throws ConversionException */ public void convert(InputStream instream, Format fromFormat, Format toFormat, OutputStream os) throws IOException, ConversionException { checkParameters(fromFormat, toFormat); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = getUrlForFormat(toFormat); BasicHttpEntity reqEntity = new BasicHttpEntity(); reqEntity.setContentType(map(fromFormat).getMimeType()); // messy that API is different to FileEntity reqEntity.setContent(instream); httppost.setEntity(reqEntity); execute(httpclient, httppost, os); } finally { httpclient.close(); } }
From source file:org.sasabus.export2Freegis.network.DataReadyManager.java
@Override public void handle(HttpExchange httpExchange) throws IOException { long start = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody())); try {/*from w w w.ja v a2 s.c o m*/ StringBuilder requestStringBuff = new StringBuilder(); int b; while ((b = in.read()) != -1) { requestStringBuff.append((char) b); } Scanner sc = new Scanner(new File(DATAACKNOWLEDGE)); String rdyackstring = ""; while (sc.hasNextLine()) { rdyackstring += sc.nextLine(); } sc.close(); SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ"); Date d = new Date(); String timestamp = date_date.format(d) + "T" + date_time.format(d); timestamp = timestamp.substring(0, timestamp.length() - 2) + ":" + timestamp.substring(timestamp.length() - 2); rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length()); out.write(rdyackstring); out.flush(); long before_elab = System.currentTimeMillis() - start; DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber); String datarequest = teqrequest.datarequest(); ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest); int vtcounter = 0; if (!requestelements.isEmpty()) { Iterator<TeqObjects> iterator = requestelements.iterator(); System.out.println("Sending List of Elements!"); String geoJson = "{\"type\":\"FeatureCollection\",\"features\":["; while (iterator.hasNext()) { TeqObjects object = iterator.next(); if (object instanceof VehicleTracking) { geoJson += ((VehicleTracking) object).toGeoJson() + ","; ++vtcounter; } } if (geoJson.charAt(geoJson.length() - 1) == ',') { geoJson = geoJson.substring(0, geoJson.length() - 1); } geoJson += "]}"; System.out.println( "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )"); HttpPost subrequest = new HttpPost(DATASEND); StringEntity requestEntity = new StringEntity(geoJson, ContentType.create("application/json", "UTF-8")); CloseableHttpClient httpClient = HttpClients.createDefault(); subrequest.setEntity(requestEntity); long after_elab = System.currentTimeMillis() - start; CloseableHttpResponse response = httpClient.execute(subrequest); //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode()); //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase()); httpClient.close(); long before_db = System.currentTimeMillis() - start; dbmanager.insertIntoDatabase(requestelements); System.out.format( "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d", before_elab, after_elab, before_db, (System.currentTimeMillis() - start), Thread.currentThread().getName(), requestelements.size()); System.out.println(""); } } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(-1); return; } finally { if (in != null) in.close(); if (out != null) out.close(); if (httpExchange != null) httpExchange.close(); } }