List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:com.hazelcast.test.starter.HazelcastVersionLocator.java
private static File downloadFile(String url, File targetDirectory, String filename) { CloseableHttpClient client = HttpClients.createDefault(); File targetFile = new File(targetDirectory, filename); if (targetFile.isFile() && targetFile.exists()) { return targetFile; }// w w w. j av a 2 s . c o m HttpGet request = new HttpGet(url); try { CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() != SC_OK) { throw new GuardianException("Cannot download file from " + url + ", http response code: " + response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); FileOutputStream fos = new FileOutputStream(targetFile); entity.writeTo(fos); fos.close(); targetFile.deleteOnExit(); return targetFile; } catch (IOException e) { throw rethrowGuardianException(e); } finally { try { client.close(); } catch (IOException e) { // ignore } } }
From source file:communication.Communicator.java
/** * Adds a new trackingPosition to an existing cartracker * * @param tracker The cartracker with a new trackingPosition * @return The serialnumber of the new trackingPosition * @throws IOException//from w w w. j a v a2 s. c om */ public static Long postTrackingPositionsForTracker(CarTracker tracker) throws IOException { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create(); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(BASE_URL_PRODUCTION + "/" + tracker.getId() + "/movements"); String jsonBody = gson.toJson(tracker.getCurrentTrackingPeriod()); StringEntity postingString = new StringEntity(jsonBody, CHARACTER_SET); post.setEntity(postingString); post.setHeader(HTTP.CONTENT_TYPE, "application/json"); HttpResponse response = httpClient.execute(post); String responseString = EntityUtils.toString(response.getEntity(), CHARACTER_SET); JSONObject json = new JSONObject(responseString); return json.getLong("serialNumber"); }
From source file:com.ibm.CloudResourceBundle.java
private static Rows getServerResponse(CloudDataConnection connect) throws Exception { Rows rows = null;//from w w w .j a v a2 s.c om CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("provide.castiron.com", 443), new UsernamePasswordCredentials(connect.getUserid(), connect.getPassword())); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try { // Call the service and get all the strings for all the languages HttpGet httpget = new HttpGet(connect.getURL()); httpget.addHeader("API_SECRET", connect.getSecret()); CloseableHttpResponse response = httpclient.execute(httpget); try { InputStream in = response.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); rows = mapper.readValue(new InputStreamReader(in, "UTF-8"), Rows.class); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpclient.close(); } return rows; }
From source file:com.jeecms.common.web.ClientCustomSSL.java
public static String getInSsl(String url, File pkcFile, String storeId, String params, String contentType) throws Exception { String text = ""; // ???PKCS12/*from w ww.jav a2s . c o m*/ KeyStore keyStore = KeyStore.getInstance("PKCS12"); // ?PKCS12? FileInputStream instream = new FileInputStream(pkcFile); try { // PKCS12?(ID) keyStore.load(instream, storeId.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build(); // Allow TLSv1 protocol only // TLS SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // httpclientSSLSocketFactory CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost post = new HttpPost(url); StringEntity s = new StringEntity(params, "utf-8"); if (StringUtils.isBlank(contentType)) { s.setContentType("application/xml"); } s.setContentType(contentType); post.setEntity(s); HttpResponse res = httpclient.execute(post); HttpEntity entity = res.getEntity(); text = EntityUtils.toString(entity, "utf-8"); } finally { httpclient.close(); } return text; }
From source file:org.cloudsimulator.utility.RestAPI.java
private static CloseableHttpResponse getRequestBasicAuth(final CloseableHttpClient httpClient, final String uri, final String username, final String password, final String contentType) throws IOException { HttpGet httpGet = new HttpGet(uri); httpGet.addHeader(ACCEPT, contentType); httpGet.addHeader(AUTHORIZATION, getBasicAuth(username, password)); return httpClient.execute(httpGet); }
From source file:com.ibm.watson.movieapp.dialog.rest.UtilityFunctions.java
/** * Makes HTTP POST request// w ww . ja v a2 s . c o m * <p> * This makes HTTP POST requests to the url provided. * * @param httpClient the http client used to make the request * @param url the url for the request * @param nvps the {name, value} pair parameters to be embedded in the request * @return the JSON object response * @throws ClientProtocolException if it is unable to execute the call * @throws IOException if it is unable to execute the call * @throws IllegalStateException if the input stream could not be parsed correctly * @throws HttpException if the HTTP call responded with a status code other than 200 or 201 */ public static JsonObject httpPost(CloseableHttpClient httpClient, String url, List<NameValuePair> nvps) throws ConnectException, ClientProtocolException, IOException, IllegalStateException, HttpException { HttpPost httpPost = new HttpPost(url); if (nvps != null) { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } try (CloseableHttpResponse response = httpClient.execute(httpPost)) { return parseHTTPResponse(response, url); } }
From source file:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse reScan(String sha256) { try {/*from w w w . j a v a2s .co m*/ CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/rescan"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addTextBody("resource", sha256); HttpEntity multipart = builder.build(); httpsScanFilePost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpsScanFilePost); return response; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; }
From source file:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse getReport(String sha256) { try {//from w ww . jav a 2s .c o m CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/report"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addTextBody("resource", sha256); HttpEntity multipart = builder.build(); httpsScanFilePost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpsScanFilePost); return response; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; }
From source file:httpServerClient.app.QuickStart.java
public static void sendMessage(String[] args) throws Exception { // arguments to run Quick start POST: // args[0] POST // args[1] IPAddress of server // args[2] port No. // args[3] user name // args[4] myMessage CloseableHttpClient httpclient = HttpClients.createDefault(); try {/* www . j a v a2 s. c o m*/ HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage"); // httpPost.setEntity(new StringEntity("lubo je kral")); httpPost.setEntity( new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}")); CloseableHttpResponse response1 = httpclient.execute(httpPost); // The underlying HTTP connection is still held by the response // object // to allow the response content to be streamed directly from the // network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally // clause. // Please note that if response content is not fully consumed the // underlying // connection cannot be safely re-used and will be shut down and // discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:com.lagrange.LabelApp.java
/** * Try to send message with labels and its probabilities to telegram *//*from ww w. j a v a 2 s. c om*/ private static void sendMessageToTelegramBot(List<EntityAnnotation> labels) throws IOException { String urlSendMessage = "https://api.telegram.org/" + BOT_ID + "/sendMessage"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlSendMessage); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("text", buildMessage(labels))); nvps.add(new BasicNameValuePair("chat_id", CHAT_ID)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); } finally { response.close(); } System.out.println("Done sending text"); }