List of usage examples for org.apache.http.impl.client CloseableHttpClient close
public void close() throws IOException;
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);/*from ww w . j av a 2 s . co m*/ data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }
From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java
@Test(groups = "wso2.as", description = "Verfiy Spring Request scope") public void testSpringRequestScope() throws Exception { String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/request"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet(endpoint); HttpResponse response1 = httpClient.execute(httpget, httpContext); String responseMsg1 = new BasicResponseHandler().handleResponse(response1); HttpResponse response2 = httpClient.execute(httpget, httpContext); String responseMsg2 = new BasicResponseHandler().handleResponse(response2); httpClient.close(); assertTrue(!responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should not be the same"); }
From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java
@Test(groups = "wso2.as", description = "Verfiy Spring Session scope") public void testSpringSessionScope() throws Exception { String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/session"; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet(endpoint); HttpResponse response1 = httpClient.execute(httpget, httpContext); String responseMsg1 = new BasicResponseHandler().handleResponse(response1); HttpResponse response2 = httpClient.execute(httpget, httpContext); String responseMsg2 = new BasicResponseHandler().handleResponse(response2); httpClient.close(); assertTrue(responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should be the same"); }
From source file:org.apache.synapse.samples.framework.clients.BasicHttpClient.java
/** * Make a HTTP POST request on the specified URL. * * @param url A valid HTTP URL/*www.j av a2s . c om*/ * @param payload An array of bytes to be posted to the URL (message body) * @param contentType Content type of the message body * @param headers A map of HTTP headers to be set on the outgoing request * @return A HttpResponse object * @throws Exception If an error occurs while making the HTTP call */ public HttpResponse doPost(String url, byte[] payload, String contentType, Map<String, String> headers) throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); try { HttpPost post = new HttpPost(url); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { post.setHeader(entry.getKey(), entry.getValue()); } } BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentType(contentType); entity.setContent(new ByteArrayInputStream(payload)); post.setEntity(entity); return new HttpResponse(client.execute(post)); } finally { client.close(); } }
From source file:com.enioka.jqm.tools.JettyTest.java
@Test public void testSslServices() throws Exception { Helpers.setSingleParam("enableWsApiSsl", "true", em); Helpers.setSingleParam("disableWsApi", "false", em); Helpers.setSingleParam("enableWsApiAuth", "false", em); addAndStartEngine();/*w ww .j ava2 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); // HTTPS client - with KeyStore trustStore = KeyStore.getInstance("JKS"); FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks")); try { trustStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).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); jqmlogger.debug(rq.getURI()); CloseableHttpResponse rs = cl.execute(rq); Assert.assertEquals(200, rs.getStatusLine().getStatusCode()); rs.close(); cl.close(); }
From source file:org.eclipse.emf.ecp.emf2web.json.JSONCrudOperator.java
private Map<String, Object> sendPost(String completeUrl, Map<String, Object> element) throws IOException { final CloseableHttpClient httpClient = HttpClients.createDefault(); try {/*from ww w.ja v a 2 s.com*/ final HttpPost postRequest = new HttpPost(completeUrl); final Gson gson = new GsonBuilder().create(); final String json = gson.toJson(element); postRequest.setEntity(new StringEntity(json, ContentType.create("application/json"))); final JSONResponseHandler<Map<String, Object>> responseHandler = new JSONResponseHandler<Map<String, Object>>(); final Map<String, Object> response = responseHandler.handleResponse(httpClient.execute(postRequest)); return response; } finally { httpClient.close(); } }
From source file:org.eclipse.emf.ecp.emf2web.json.JSONCrudOperator.java
public List<Map<String, Object>> readElements(String url, String type) throws IOException { final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); final CloseableHttpClient httpClient = HttpClients.createDefault(); try {//from w w w . ja v a 2 s. c o m final HttpGet httpGet = new HttpGet(url + "/" + type); final JSONResponseHandler<List<Map<String, Object>>> responseHandler = new JSONResponseHandler<List<Map<String, Object>>>(); final List<Map<String, Object>> resultList = responseHandler .handleResponse(httpClient.execute(httpGet)); for (final Map<String, Object> object : resultList) { if (object == null) { continue; } result.add(object); } } finally { httpClient.close(); } return result; }
From source file:cat.calidos.morfeu.utils.injection.DataFetcherModule.java
@Produces @Named("httpData") public InputStream fetchHttpData(CloseableHttpClient client, HttpGet request) throws FetchingException { try {//from w w w . ja va2s . c om log.trace("Fetching http data from {}", request.getURI()); // we want to close right now so we fetch all the content and close the input stream InputStream content = client.execute(request).getEntity().getContent(); InputStream fetchedData = IOUtils.toBufferedInputStream(content); return fetchedData; } catch (Exception e) { throw new FetchingException("Problem fetching http data", e); } finally { if (client != null) { try { client.close(); } catch (IOException e) { throw new FetchingException("Problem closing client when fetching http data", e); } } } }
From source file:com.rockagen.commons.http.HttpConn.java
/** * Handler main/* ww w .j a v a 2s . c om*/ * * @param targetHost target {@link HttpHost} * @param proxyHost proxy {@link HttpHost} * @param httpRequestMethod HttpGet or HttpPost... * @param encoding encoding * @param upc {@link UsernamePasswordCredentials} * @param keystore keystore stream * @param password keystore password * @return result String * @throws IOException if an I/O error occurs */ protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod, String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password) throws IOException { HttpClientBuilder hcb = HttpClients.custom(); hcb.setDefaultRequestConfig(getRequestConfig()); if (proxyHost != null) { hcb.setProxy(proxyHost); } if (keystore != null) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(keystore, password); SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext); hcb.setSSLSocketFactory(ssf); } catch (KeyStoreException e) { log.error("{}", e.getMessage(), e); } catch (CertificateException e) { log.error("{}", e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error("{}", e.getMessage(), e); } catch (KeyManagementException e) { log.error("{}", e.getMessage(), e); } finally { keystore.close(); } } if (upc != null) { CredentialsProvider cp = new BasicCredentialsProvider(); AuthScope as = new AuthScope(targetHost); cp.setCredentials(as, upc); hcb.setDefaultCredentialsProvider(cp); } CloseableHttpClient chc = hcb.build(); try { CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod); return getResponse(response, encoding); } finally { chc.close(); } }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Make the specified request with the specified client context. * <p>/* ww w.j av a 2s . com*/ * The specified cookies will be added to the request. A request will be aborted if it exceeds the specified timeout. * Non Json responses are converted and thrown as RestExceptions. * <p> * Ensures that all closable resources are closed. * * @param httpRequest The request to execute. * @param context The context to use when executing the request. * @param timeout The maximum time in milliseconds the request is allowed to take. * @param cookiesToProxy The cookies to add to the request. * @return The Rest response. * @throws RestException Thrown if the request exceeds the specified timeout, or a non Json response is received. * @throws IOException */ public RestResponse callRestEndPoint(HttpRequestBase httpRequest, HttpClientContext context, int timeout, List<KeyValuePair> cookiesToProxy) throws RestException, IOException { CookieStore cookieStore = buildCookieStore(httpRequest.getURI().getHost(), cookiesToProxy); CloseableHttpClient closeableHttpClient = getHttpClient(cookieStore); try { CloseableHttpResponse closeableHttpResponse = executeRequest(closeableHttpClient, httpRequest, context, timeout); try { RestResponse restResponse = buildRestResponse(httpRequest, closeableHttpResponse); checkRestResponse(restResponse); return restResponse; } finally { closeableHttpResponse.close(); } } finally { closeableHttpClient.close(); } }