List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:org.opennms.poller.remote.MetadataUtils.java
public static Map<String, String> fetchGeodata() { final Map<String, String> ret = new HashMap<>(); final String url = "http://freegeoip.net/xml/"; final CloseableHttpClient httpclient = HttpClients.createDefault(); final HttpGet get = new HttpGet(url); CloseableHttpResponse response = null; try {// w w w. j a v a 2 s . c o m response = httpclient.execute(get); final HttpEntity entity = response.getEntity(); final String xml = EntityUtils.toString(entity); System.err.println("xml = " + xml); final GeodataResponse geoResponse = JaxbUtils.unmarshal(GeodataResponse.class, xml); ret.put("external-ip-address", InetAddressUtils.str(geoResponse.getIp())); ret.put("country-code", geoResponse.getCountryCode()); ret.put("region-code", geoResponse.getRegionCode()); ret.put("city", geoResponse.getCity()); ret.put("zip-code", geoResponse.getZipCode()); ret.put("time-zone", geoResponse.getTimeZone()); ret.put("latitude", geoResponse.getLatitude() == null ? null : geoResponse.getLatitude().toString()); ret.put("longitude", geoResponse.getLongitude() == null ? null : geoResponse.getLongitude().toString()); EntityUtils.consumeQuietly(entity); } catch (final Exception e) { LOG.debug("Failed to get GeoIP data from " + url, e); } finally { IOUtils.closeQuietly(response); } return ret; }
From source file:com.networknt.light.server.handler.loader.MenuLoader.java
private static void loadMenuFile(File file) { Scanner scan = null;/*from w ww. j av a 2s . c om*/ try { scan = new Scanner(file, Loader.encoding); // the content is only the data portion. convert to map String content = scan.useDelimiter("\\Z").next(); HttpPost httpPost = new HttpPost("http://injector:8080/api/rs"); StringEntity input = new StringEntity(content); input.setContentType("application/json"); httpPost.setEntity(input); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent())); String json = ""; String line = ""; while ((line = rd.readLine()) != null) { json = json + line; } System.out.println("json = " + json); EntityUtils.consume(entity); } finally { response.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (scan != null) scan.close(); } }
From source file:com.ibm.CloudResourceBundle.java
private static Rows getServerResponse(CloudDataConnection connect) throws Exception { Rows rows = null;/*ww w .j a va2 s.co m*/ 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.networknt.light.server.handler.loader.Loader.java
public static void login(String host, String userId, String password) throws Exception { Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("category", "user"); inputMap.put("name", "signInUser"); inputMap.put("readOnly", false); Map<String, Object> data = new HashMap<String, Object>(); data.put("userIdEmail", userId); data.put("password", password); data.put("rememberMe", true); data.put("clientId", "example@Browser"); inputMap.put("data", data); HttpPost httpPost = new HttpPost(host + "/api/rs"); StringEntity input = new StringEntity( ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap)); input.setContentType("application/json"); httpPost.setEntity(input);// w ww .j a va 2 s. c o m CloseableHttpResponse response = httpclient.execute(httpPost); try { //System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent())); String json = ""; String line = ""; while ((line = rd.readLine()) != null) { json = json + line; } //System.out.println("json = " + json); Map<String, Object> jsonMap = ServiceLocator.getInstance().getMapper().readValue(json, new TypeReference<HashMap<String, Object>>() { }); jwt = (String) jsonMap.get("accessToken"); EntityUtils.consume(entity); } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } }
From source file:io.undertow.server.handlers.URLDecodingHandlerTestCase.java
private static String getResponseString(CloseableHttpResponse response) throws IOException { Assert.assertEquals(200, response.getStatusLine().getStatusCode()); return IOUtils.toString(response.getEntity().getContent(), "UTF-8"); }
From source file:io.hightide.TemplateFetcher.java
private static void httpGetTemplate(Path tempFile, String url) throws IOException { CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url)); byte[] buffer = new byte[BUFFER]; try (InputStream input = response.getEntity().getContent(); OutputStream output = new FileOutputStream(tempFile.toFile())) { for (int length; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); }/* w w w. j ava 2s. co m*/ } }
From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java
/** * Download from given URL to given file location. * @param url String//from w w w . j a v a 2 s.c o m * @param filepath String * @return */ public static String download(String url, String filepath) { String status = ""; try { CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (filepath == null) { filepath = getFilePath(response); //NOSONAR } File file = new File(filepath); file.getParentFile().mkdirs(); FileOutputStream fileout = new FileOutputStream(file); byte[] buffer = new byte[CACHE]; int ch; while ((ch = is.read(buffer)) != -1) { fileout.write(buffer, 0, ch); } is.close(); fileout.flush(); fileout.close(); status = Constant.DOWNLOADCSAR_SUCCESS; } catch (Exception e) { status = Constant.DOWNLOADCSAR_FAIL; LOG.error("Download csar file failed! " + e.getMessage(), e); } return status; }
From source file:org.codehaus.mojo.license.utils.HttpRequester.java
/** * this method will send a simple GET-request to the given destination and will return the result as a * string/*from w ww.ja v a 2 s . c o m*/ * * @param url the resource destination that is expected to contain pure text * @return the string representation of the resource at the given URL */ public static String getFromUrl(String url) throws MojoExecutionException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); CloseableHttpResponse response = null; String result = null; try { response = httpClient.execute(get); result = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")); } catch (ClientProtocolException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (response != null) { try { response.close(); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } } return result; }
From source file:com.econcept.pingconnectionutility.utility.PingConnectionUtility.java
private static void httpPingable(String targetURI) throws IOException, URISyntaxException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(targetURI)); CloseableHttpResponse response = httpClient.execute(httpGet); int currentCode = response.getStatusLine().getStatusCode(); try {/*from w w w.ja va 2s . co m*/ if (currentCode >= 200 && currentCode < 300) { HttpEntity entity = response.getEntity(); InputStream responseStream = entity.getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(responseStream, writer, "UTF-8"); System.out.println("Target Server are ok: " + currentCode); System.out.println(writer.toString()); EntityUtils.consume(entity); } // if else { System.out.println("Target Server are not ok: " + currentCode); } // else } // try finally { response.close(); } // finally }
From source file:com.farsunset.cim.util.MessageDispatcher.java
private static String httpPost(String url, Message msg) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("mid", msg.getMid())); nvps.add(new BasicNameValuePair("extra", msg.getExtra())); nvps.add(new BasicNameValuePair("action", msg.getAction())); nvps.add(new BasicNameValuePair("title", msg.getTitle())); nvps.add(new BasicNameValuePair("content", msg.getContent())); nvps.add(new BasicNameValuePair("sender", msg.getSender())); nvps.add(new BasicNameValuePair("receiver", msg.getReceiver())); nvps.add(new BasicNameValuePair("timestamp", String.valueOf(msg.getTimestamp()))); httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); CloseableHttpResponse response2 = httpclient.execute(httpPost); String data = null;/*from w w w . jav a 2s. c om*/ try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); data = EntityUtils.toString(entity2); } finally { response2.close(); } return data; }