List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:br.cefetrj.sagitarii.nunki.comm.WebClient.java
public void doPost(String action, String parameter, String content) throws Exception { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(gf.getHostURL() + "/" + action); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair(parameter, content)); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); httpClient.execute(httppost);//from ww w. j a va2 s. c om httpClient.close(); }
From source file:moxy.ProxyHttpAppTest.java
@Test public void canProxyGetRequests() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://localhost:6565/healthcheck"); CloseableHttpResponse response = httpclient.execute(request); try {//w w w . j a v a2 s . com assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("{\"deadlocks\":{\"healthy\":true}}", EntityUtils.toString(response.getEntity())); assertableListener.assertConnectionWasMadeOn(6565); } finally { httpclient.close(); } }
From source file:org.sead.repositories.reference.util.SEADAuthenticator.java
static public HttpClientContext authenticate(String server) { boolean authenticated = false; log.info("Authenticating"); String accessToken = SEADGoogleLogin.getAccessToken(); // Now login to server and create a session CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from www . ja v a 2 s. c o m*/ // //DoLogin is the auth endpoint when using the AUthFilter, versus // the api/authenticate endpoint when connecting to the ACR directly HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin"); List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1); nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken)); seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList)); CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // String seadSessionId = // EntityUtils.toString(resEntity); authenticated = true; } } else { // Seems to occur when google device id is not set on server // - with a Not Found response... log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Cannot read sead-google.json"); log.error(e.getMessage()); } // localContext should have the cookie with the SEAD session key, which // nominally is all that's needed. // FixMe: If there is no activity for more than 15 minutes, the session // may expire, in which case, // re-authentication using the refresh token to get a new google token // to allow SEAD login again may be required // also need to watch the 60 minutes google token timeout - project // spaces will invalidate the session at 60 minutes even if there is // activity authTime = System.currentTimeMillis(); if (authenticated) { return localContext; } return null; }
From source file:com.kingmed.dp.ndp.job.NDPServeMonitorJob.java
private String execute(String uri, ResponseHandler<String> responeHandler, Header header) throws IOException { String re = null;/*from w w w .j a v a 2 s . co m*/ CloseableHttpClient httpClient = null; HttpGet httpGet = null; httpClient = HttpClients.createDefault(); httpGet = new HttpGet(uri); if (header != null) { httpGet.setHeader(header.getName(), header.getValue()); } try { re = httpClient.execute(httpGet, responeHandler); } finally { if (httpClient != null) { httpClient.close(); } } return re; }
From source file:com.scottjjohnson.finance.analysis.HttpClient.java
/** * Executes a HTTP GET request.// w ww . jav a 2 s . c om * * @param url * URL with optional query parameters * @return response body * @throws IOException * if the HTTP request fails */ public String sendGetRequest(String url) throws IOException { // I'm not using try-with-resources because I want to handle an exception on close() differently than other // exceptions. Other exceptions are allowed to bubble up. CloseableHttpClient apacheHttpClient = HttpClients.createDefault(); String responseBody = null; LOGGER.debug("URL = {}", url); try { HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); responseBody = apacheHttpClient.execute(httpGet, responseHandler); } finally { try { apacheHttpClient.close(); } catch (IOException e) { LOGGER.debug("Non-fatal exception: Caught IOException when calling ClosableHttpClient.close().", e); } } LOGGER.debug("HTTP Response body = {}", responseBody); return responseBody; }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do delete./*ww w. j ava2 s.c om*/ * * @param uri the uri * @param headers the headers * @return the http get simple resp * @throws ClientProtocolException the client protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws HttpResponseException the http response exception */ public static HttpGetSimpleResp doDelete(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpDelete httpDelete = new HttpDelete(uri); for (String key : headers.keySet()) { httpDelete.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpDelete); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future resp.setResult(new BasicResponseHandler().handleResponse(response)); } EntityUtils.consume(entity); } finally { response.close(); } } else { // TODO optimiz (repeating code) throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java
private static File download(File file, URL url) { CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; OutputStream out = null;/* ww w.j a v a 2s .c o m*/ file.getParentFile().mkdirs(); try { HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); Builder builder = RequestConfig.custom(); HttpHost proxy = getProxy(target); if (proxy != null) { builder = builder.setProxy(proxy); } RequestConfig config = builder.build(); HttpGet request = new HttpGet(url.toURI()); request.setConfig(config); response = httpclient.execute(target, request); InputStream in = response.getEntity().getContent(); out = new BufferedOutputStream(new FileOutputStream(file)); copy(in, out); return file; } catch (Exception e) { logWarning(e); ; } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (response != null) { try { response.close(); } catch (IOException e) { } } try { httpclient.close(); } catch (IOException e) { } } return null; }
From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.headers.CookieHeaderServletTestCase.java
@ATTest({ "modules/testcases/jdkAll/Wildfly/web/src/main/java#13.0.0", "modules/testcases/jdkAll/Eap71x-Proposed/web/src/main/java#7.1.4", "modules/testcases/jdkAll/Eap71x/web/src/main/java#7.1.4" }) @OperateOnDeployment(DEPLOYMENT)/*w w w . j a v a 2s .c om*/ public void headerProtocolTest(@ArquillianResource URL url) throws Exception { URL testURL = new URL(url.toString() + "cookieHeaderServlet"); final HttpGet request = new HttpGet(testURL.toString()); request.setProtocolVersion(HttpVersion.HTTP_1_0); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; response = httpClient.execute(request); System.out.println("Protocol Version : " + response.getProtocolVersion()); Assert.assertTrue("Protocol Version should be HTTP/1.1.", response.getProtocolVersion().toString().contains("HTTP/1.1")); IOUtils.closeQuietly(response); httpClient.close(); }
From source file:org.ireas.intuition.IntuitionLoader.java
private String loadString() throws IOException { // TODO fix SNI / invalid handshake System.setProperty("jsse.enableSNIExtension", "false"); String urlString = String.format(getIntuitionUrl(), domain, language); URI uri;//from w ww . ja v a 2s .c o m try { uri = new URI(urlString); } catch (URISyntaxException exception) { // Should not occur: The initial URI is valid, and setIntuitionUrl // checks the validity of the new URI throw new AssertionError("Invalid URI", exception); } CloseableHttpClient client = HttpClients.createDefault(); String result; try { HttpGet request = new HttpGet(uri); HttpResponse httpResponse = client.execute(request); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); } finally { client.close(); } return result; }
From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java
@Test @SuppressWarnings("deprecation") public void testSSLSystemProperties() throws IOException { CloseableHttpClient client = HttpClientUtil.createClient(null); try {/*from www . j av a2 s . co m*/ SSLTestConfig.setSSLSystemProperties(); assertNotNull("HTTPS scheme could not be created using the javax.net.ssl.* system properties.", client.getConnectionManager().getSchemeRegistry().get("https")); System.clearProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME); client.close(); client = HttpClientUtil.createClient(null); assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass()); System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "true"); client.close(); client = HttpClientUtil.createClient(null); assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass()); System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, ""); client.close(); client = HttpClientUtil.createClient(null); assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass()); System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "false"); client.close(); client = HttpClientUtil.createClient(null); assertEquals(AllowAllHostnameVerifier.class, getHostnameVerifier(client).getClass()); } finally { SSLTestConfig.clearSSLSystemProperties(); System.clearProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME); client.close(); } }