List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:processingtest.CitySense.java
public ArrayList<CityData> getDayDataByLocation() throws IOException { String query = queryBuilder.getDayDataByLocation(2); //Over 2 days CloseableHttpResponse response = this.executeRequest(query); HttpEntity entity = response.getEntity(); ArrayList<CityData> dataPoints = null; if (entity != null) { try ( // A Simple JSON Response Read InputStream instream = entity.getContent()) { String result = convertStreamToString(instream); // now you have the string representation of the HTML request //System.out.println("RESPONSE: " + result); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(result); JSONObject jobj = (JSONObject) obj; //System.out.println(jobj.entrySet()); Object dataObject = jobj.get("data"); JSONArray array = (JSONArray) dataObject; //System.out.println(array.get(0)); dataPoints = decodeJsonData(array); System.out.println((dataPoints.size())); } catch (ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); }/* w w w . j a v a2 s. c om*/ } } return dataPoints; }
From source file:processingtest.CitySense.java
public ArrayList<CityData> getDayDataBySource() throws URISyntaxException, IOException { String query = queryBuilder.getDayDataBySource(2); //Over 2 days CloseableHttpResponse response = this.executeRequest(query); HttpEntity entity = response.getEntity(); ArrayList<CityData> dataPoints = null; if (entity != null) { try ( // A Simple JSON Response Read InputStream instream = entity.getContent()) { String result = convertStreamToString(instream); // now you have the string representation of the HTML request //System.out.println("RESPONSE: " + result); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(result); JSONObject jobj = (JSONObject) obj; //System.out.println(jobj.entrySet()); Object dataObject = jobj.get("data"); JSONArray array = (JSONArray) dataObject; //System.out.println(array.get(0)); dataPoints = decodeJsonData(array); System.out.println((dataPoints.size())); } catch (ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); }/* www. j a va 2 s.c o m*/ } } return dataPoints; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ZonesTest.java
@Test public void itGetsStatsForZones() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:3333/crs/stats/zones/caches"); CloseableHttpResponse response = null; try {//from ww w . ja v a 2 s .c om response = httpClient.execute(httpGet); String actual = EntityUtils.toString(response.getEntity()); Map<String, Object> zoneStats = new ObjectMapper().readValue(actual, new TypeReference<HashMap<String, Object>>() { }); Map<String, Object> dynamicZonesStats = (Map<String, Object>) zoneStats.get("dynamicZoneCaches"); assertThat(dynamicZonesStats.keySet(), containsInAnyOrder("requestCount", "evictionCount", "totalLoadTime", "averageLoadPenalty", "hitCount", "loadSuccessCount", "missRate", "loadExceptionRate", "hitRate", "missCount", "loadCount", "loadExceptionCount")); Map<String, Object> staticZonesStats = (Map<String, Object>) zoneStats.get("staticZoneCaches"); assertThat(staticZonesStats.keySet(), containsInAnyOrder("requestCount", "evictionCount", "totalLoadTime", "averageLoadPenalty", "hitCount", "loadSuccessCount", "missRate", "loadExceptionRate", "hitRate", "missCount", "loadCount", "loadExceptionCount")); } finally { if (response != null) response.close(); } }
From source file:org.ow2.proactive.http.CommonHttpResourceDownloader.java
public String getResource(String sessionId, String url, boolean insecure) throws IOException { CommonHttpClientBuilder builder = new CommonHttpClientBuilder().maxConnections(CONNECTION_POOL_SIZE) .useSystemProperties().insecure(insecure); try (CloseableHttpClient client = builder.build()) { CloseableHttpResponse response = createAndExecuteRequest(sessionId, url, client); return readContent(response.getEntity().getContent()); }// w ww .ja va 2 s. co m }
From source file:org.springside.examples.oadata.service.TenderViewService.java
public Result synTenderProccess(TenderView tenderView) { boolean result = false; //??/* w ww.j a va 2 s.co m*/ StringWriter writer = new StringWriter(); BodyXml<TenderView> bodyXml = new BodyXml<TenderView>(); bodyXml.setProjectInfo(tenderView); ; SupplierXml supplierXml = new SupplierXml(); supplierXml.setBody(bodyXml); try { marshaller.marshal(supplierXml, writer); } catch (JAXBException e) { logger.error("{}|{}XML?:" + e.getStackTrace(), tenderView.getTenderId(), tenderView.getTenderName()); } try { HttpPost httpPost = new HttpPost(propertiesLoader.getProperty("syn.synSupplierUrl")); // ??/ List<NameValuePair> parameters = new ArrayList<NameValuePair>(); String xmlContent = writer.toString(); parameters.add(new BasicNameValuePair("xmlContent", xmlContent)); // UrlEncodedFormEntity UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, "UTF-8"); httpPost.setEntity(formEntiry); // ?connection poolclient CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost); closeableHttpResponse.getEntity().getContent(); String xmlContentresp = IOUtils.toString(closeableHttpResponse.getEntity().getContent()); if (xmlContentresp.contains("operTag")) { String operTag = StringUtils.substringBetween(xmlContentresp, "<operTag>", "</operTag>"); String operDesc = StringUtils.substringBetween(xmlContentresp, "<operDesc>", "</operDesc>"); if ("Y".equals(operTag)) {//? result = true; } else { logger.error("?{}|{}??{}", tenderView.getTenderId(), tenderView.getTenderName(), operDesc); } } closeableHttpResponse.close(); } catch (IOException e) { e.printStackTrace(); logger.error("?{}|{}??:" + e.getStackTrace(), tenderView.getTenderId(), tenderView.getTenderName()); } return new Result(result, null); }
From source file:cf.spring.servicebroker.AbstractServiceBrokerTest.java
protected JsonNode loadCatalog(CloseableHttpClient client) throws IOException { final HttpUriRequest catalogRequest = RequestBuilder.get() .setUri("http://localhost:8080" + Constants.CATALOG_URI).build(); final CloseableHttpResponse response = client.execute(catalogRequest); assertEquals(response.getStatusLine().getStatusCode(), 200); final String body = StreamUtils.copyToString(response.getEntity().getContent(), Charset.defaultCharset()); final ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(body); }
From source file:ar.edu.ubp.das.src.chat.actions.ActualizarUsuariosAction.java
@Override public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response) throws SQLException, RuntimeException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { //prepare http get SalaBean sala = (SalaBean) request.getSession().getAttribute("sala"); String ultima_actualizacion = String.valueOf(request.getSession().getAttribute("ultima_actualizacion")); String authToken = String.valueOf(request.getSession().getAttribute("token")); if (ultima_actualizacion.equals("null") || ultima_actualizacion.isEmpty()) { ultima_actualizacion = String.valueOf(System.currentTimeMillis()); }//w w w . j a va 2 s . c om URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("25.136.78.82").setPort(8080) .setPath("/actualizaciones/sala/" + sala.getId()); builder.setParameter("ultima_act", ultima_actualizacion); HttpGet getRequest = new HttpGet(); getRequest.setURI(builder.build()); getRequest.addHeader("Authorization", "BEARER " + authToken); getRequest.addHeader("accept", "application/json; charset=ISO-8859-1"); CloseableHttpResponse getResponse = httpClient.execute(getRequest); HttpEntity responseEntity = getResponse.getEntity(); StatusLine responseStatus = getResponse.getStatusLine(); String restResp = EntityUtils.toString(responseEntity); if (responseStatus.getStatusCode() != 200) { throw new RuntimeException(restResp); } if (restResp.equals("null") || restResp.isEmpty()) { return mapping.getForwardByName("success"); } //parse actualizacion data from response Gson gson = new Gson(); Type listType = new TypeToken<LinkedList<ActualizacionBean>>() { }.getType(); List<ActualizacionBean> actualizaciones = gson.fromJson(restResp, listType); List<UsuarioBean> usuarios = actualizaciones.stream() .filter(a -> a.getNombre_tipo().equals("UsuarioSala")).map(m -> m.getUsuario()) .collect(Collectors.toList()); request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis())); if (!usuarios.isEmpty()) { request.setAttribute("usuarios", usuarios); } return mapping.getForwardByName("success"); } catch (IOException | URISyntaxException | RuntimeException e) { SalaBean sala = (SalaBean) request.getSession().getAttribute("sala"); request.setAttribute("message", "Error al intentar actualizar usuarios de Sala " + sala.getId() + ": " + e.getMessage()); response.setStatus(400); return mapping.getForwardByName("failure"); } }
From source file:org.wso2.carbon.dynamic.client.web.proxy.RegistrationProxy.java
@DELETE @Produces(MediaType.APPLICATION_JSON)//from w w w . jav a 2 s.com public Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, @QueryParam("consumerKey") String consumerKey) { Response response; DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient(); String host = DCRProxyUtils.getKeyManagerHost(); try { URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL) .setHost(host).setPath(Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) .setParameter("applicationName", applicationName).setParameter("userId", userId) .setParameter("consumerKey", consumerKey).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse serverResponse = httpClient.execute(httpDelete); HttpEntity responseData = serverResponse.getEntity(); int status = serverResponse.getStatusLine().getStatusCode(); String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8); response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); } catch (URISyntaxException e) { String msg = "Server error occurred while deleting the client '" + applicationName + "'"; log.error(msg, e); response = Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (UnsupportedEncodingException e) { String msg = "Request data encoding error occurred while deleting the client '" + applicationName + "'"; log.error(msg, e); response = Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity(msg).build(); } catch (IOException e) { String msg = "Service invoke error occurred while deleting the client '" + applicationName + "'"; log.error(msg, e); response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } finally { httpClient.close(); } return response; }
From source file:io.crate.integrationtests.RestSQLActionIntegrationTest.java
@Test public void testWithInvalidPayload() throws IOException { CloseableHttpResponse response = post("{\"foo\": \"bar\"}"); assertEquals(400, response.getStatusLine().getStatusCode()); String bodyAsString = EntityUtils.toString(response.getEntity()); assertThat(bodyAsString, startsWith("{\"error\":{\"message\":\"SQLActionException[Failed to parse source" + " [{\\\"foo\\\": \\\"bar\\\"}]]\",\"code\":4000},\"error_trace\":\"")); }