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.beginner.core.utils.HttpUtil.java
/** * <p>To request the GET way.</p> * //from ww w. jav a 2s. co m * @param url request URI * @param timeout request timeout time in milliseconds(The default timeout time for 30 seconds.) * @return String response result * @throws Exception * @since 1.0.0 */ public static String get(String url, Integer timeout) throws Exception { // Validates input if (StringUtils.isBlank(url)) throw new IllegalArgumentException("The url cannot be null and cannot be empty."); //The default timeout time for 30 seconds if (null == timeout) timeout = 30000; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; String result = null; try { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout) .setConnectTimeout(timeout).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); EntityUtils.consume(entity); } catch (Exception e) { logger.error("GET?", e); return null; } finally { if (null != httpResponse) httpResponse.close(); if (null != httpClient) httpClient.close(); } return result; }
From source file:DeliverWork.java
private static String getResultBody(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String resultBody = null;//from www.j av a 2 s . c om try { httpClient = HttpClients.createDefault(); // http(get?) HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); HttpEntity result = response.getEntity(); resultBody = EntityUtils.toString(result); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { e.printStackTrace(); } } return resultBody; }
From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java
private static void performPost(String url, String data) { CloseableHttpClient client = HttpClientBuilder.create().build(); try {/*from ww w .j ava 2s. c om*/ HttpPost request = new HttpPost(url); request.setEntity(new StringEntity(data, ContentType.DEFAULT_BINARY)); client.execute(request); } catch (IOException e) { // ignore silently LOG.debug("Could not execute a POST on url " + url, e); } finally { IOUtils.closeQuietly(client); } }
From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java
/** * Invoke Business Rules with JSON content * * @param content The payload of itineraries to send to Business Rules. * @return A JSON string representing the output of Business Rules. *//* w w w . ja v a 2s . c om*/ public static String invokeRulesService(String json) throws Exception { PropertiesReader constants = PropertiesReader.getInstance(); String username = constants.getStringProperty(USERNAME_KEY); String password = constants.getStringProperty(PASSWORD_KEY); String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY) + constants.getStringProperty(RULE_APP_PATH_KEY); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credentialsProvider).build(); String responseString = ""; try { HttpPost httpPost = new HttpPost(endpoint); httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING); httpPost.setEntity(jsonEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); responseString = EntityUtils.toString(entity, MessageUtils.ENCODING); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpClient.close(); } return responseString; }
From source file:org.wso2.am.integration.test.utils.http.HTTPSClientUtils.java
/** * GET function implementation/* w ww . j av a2 s . c om*/ * * @param httpClient http client to use * @param url request URL * @param headers headers to be send * @return org.apache.http.HttpResponse * @throws IOException if connection issue occurred */ private static HttpResponse sendGetRequest(CloseableHttpClient httpClient, String url, Map<String, String> headers) throws IOException { HttpGet request = new HttpGet(url); if (headers != null) { for (Map.Entry<String, String> head : headers.entrySet()) { request.addHeader(head.getKey(), head.getValue()); } } return httpClient.execute(request); }
From source file:ai.susi.server.ClientConnection.java
/** * get a redirect for an url: this method shall be called if it is expected that a url * is redirected to another url. This method then discovers the redirect. * @param urlstring//ww w . j av a 2 s.com * @param useAuthentication * @return the redirect url for the given urlstring * @throws IOException if the url is not redirected */ public static String getRedirect(String urlstring, boolean useAuthentication) throws IOException { HttpGet get = new HttpGet(urlstring); get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build()); get.setHeader("User-Agent", USER_AGENT); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(getConnctionManager(useAuthentication)) .setDefaultRequestConfig(defaultRequestConfig).build(); HttpResponse httpResponse = httpClient.execute(get); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { if (httpResponse.getStatusLine().getStatusCode() == 301) { for (Header header : httpResponse.getAllHeaders()) { if (header.getName().equalsIgnoreCase("location")) { EntityUtils.consumeQuietly(httpEntity); return header.getValue(); } } EntityUtils.consumeQuietly(httpEntity); throw new IOException("redirect for " + urlstring + ": no location attribute found"); } else { EntityUtils.consumeQuietly(httpEntity); throw new IOException( "no redirect for " + urlstring + " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase()); } } else { throw new IOException("client connection to " + urlstring + " fail: no connection"); } }
From source file:com.oakhole.voa.utils.HttpClientUtils.java
public static String post(String uri, File file) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); try {//from w ww . j a v a 2 s.co m InputStreamEntity inputStreamEntity = new InputStreamEntity(new FileInputStream(file)); //???? httpPost.setEntity(inputStreamEntity); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); return EntityUtils.toString(httpResponse.getEntity()); } catch (IOException e) { logger.error(":{}", e.getMessage()); } } catch (FileNotFoundException e) { logger.error(":{}", e.getMessage()); } return ""; }
From source file:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse scanFile(File fileToScan) { if (apiKey == null || apiKey.isEmpty()) { return null; }//from www. j ava2 s. c om try { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/scan"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addBinaryBody("file", fileToScan, ContentType.APPLICATION_OCTET_STREAM, fileToScan.getName()); 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:com.portfolio.data.utils.PostForm.java
public static boolean updateResource(String sessionid, String backend, String uuid, String lang, String json) throws Exception { /// Parse and create xml from JSON JSONObject files = (JSONObject) JSONValue.parse(json); JSONArray array = (JSONArray) files.get("files"); if ("".equals(lang) || lang == null) lang = "fr"; JSONObject obj = (JSONObject) array.get(0); String ressource = ""; String attLang = " lang=\"" + lang + "\""; ressource += "<asmResource>" + "<filename" + attLang + ">" + obj.get("name") + "</filename>" + // filename "<size" + attLang + ">" + obj.get("size") + "</size>" + "<type" + attLang + ">" + obj.get("type") + "</type>" + // obj.get("url"); // Backend source, when there is multiple backend "<fileid" + attLang + ">" + obj.get("fileid") + "</fileid>" + "</asmResource>"; /// Send data to resource /// Server + "/resources/resource/file/" + uuid +"?lang="+ lang CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from w w w . java 2s . c om HttpPut put = new HttpPut("http://" + backend + "/rest/api/resources/resource/" + uuid); put.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us StringEntity se = new StringEntity(ressource); se.setContentEncoding("application/xml"); put.setEntity(se); CloseableHttpResponse response = httpclient.execute(put); try { HttpEntity resEntity = response.getEntity(); } finally { response.close(); } } finally { httpclient.close(); } return false; }
From source file:de.adesso.referencer.search.helper.ElasticConfig.java
public static String sendHttpRequest(String url, String requestBody, String requestType) throws IOException { String result = null;//from w w w . j a va 2s . c o m CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse httpResponse; try { switch (requestType) { case "Get": httpResponse = httpclient.execute(new HttpGet(url)); break; case "Post": HttpPost httppost = new HttpPost(url); if (requestBody != null) httppost.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); httpResponse = httpclient.execute(httppost); break; case "Put": HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json"); httpPut.addHeader("Accept", "application/json"); if (requestBody != null) httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET)); httpResponse = httpclient.execute(httpPut); break; case "Delete": httpResponse = httpclient.execute(new HttpDelete(url)); break; default: httpResponse = httpclient.execute(new HttpGet(url)); break; } try { HttpEntity entity1 = httpResponse.getEntity(); if (entity1 != null) { long len = entity1.getContentLength(); if (len != -1 && len < MAX_CONTENT_LENGTH) { result = EntityUtils.toString(entity1, DEFAULT_CHARSET); } else { System.out.println("Error!!!! entity length=" + len); } } EntityUtils.consume(entity1); } finally { httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } finally { httpclient.close(); } return result; }