List of usage examples for org.apache.http.util EntityUtils toString
public static String toString(HttpEntity httpEntity) throws IOException, ParseException
From source file:ch.asadzia.cognitive.EmotionDetect.java
public ServiceResult process() { HttpClient httpclient = HttpClients.createDefault(); try {//from w ww. j av a 2 s .c o m URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/octet-stream"); request.setHeader("Ocp-Apim-Subscription-Key", apikey); // Request body FileEntity reqEntity = new FileEntity(imageData); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String responseStr = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println(responseStr); return null; } JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseStr); JSONObject jsonObject = (JSONObject) jsonArray.get(0); HashMap<char[], Double> scores = (HashMap) jsonObject.get("scores"); Map.Entry<char[], Double> maxEntry = null; for (Map.Entry<char[], Double> entry : scores.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } Object key = maxEntry.getKey(); String winningEmotionName = (String) key; ServiceResult result = new ServiceResult(translateEmotion(winningEmotionName), winningEmotionName); System.out.println(responseStr); return result; } } catch (Exception e) { System.err.println(e.toString()); } return null; }
From source file:com.dc.runbook.dt.locator.RunBookLocator.java
private static String locateRunBookFileOverHttp(String uri) { String responseBody;/*from ww w. j a v a 2s. c o m*/ try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpget = new HttpGet(uri); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new RunBookException( "Unexpected response status: " + status + " while locating RunBook"); } } }; responseBody = httpClient.execute(httpget, responseHandler); } catch (IOException e) { throw new RunBookException("Unable to locate RunBook for URI : " + uri, e); } return responseBody; }
From source file:org.brunocvcunha.jiphy.requests.base.JiphyGetRequest.java
@Override public T execute() throws ClientProtocolException, IOException { HttpGet get = new HttpGet(JiphyConstants.API_URL + getUrl()); get.addHeader("Connection", "close"); get.addHeader("Accept", "*/*"); get.addHeader("Content-Type", "application/json; charset=UTF-8"); get.addHeader("Accept-Language", "en-US"); HttpResponse response = api.getClient().execute(get); api.setLastResponse(response);// w w w . j a va 2 s . c o m int resultCode = response.getStatusLine().getStatusCode(); String content = EntityUtils.toString(response.getEntity()); get.releaseConnection(); return parseResult(resultCode, content); }
From source file:com.jpa.MyHttpClient.java
public String getContent(String url) { String out = ""; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = null;/*from www. j a va 2 s .c o m*/ try { response = httpclient.execute(httpget); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpEntity entity = response.getEntity(); if (entity != null) { try { out = EntityUtils.toString(entity); Log.d("INFO", out); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return out; }
From source file:io.crate.integrationtests.RestSQLActionIntegrationTest.java
@Test public void testWithoutBody() throws IOException { CloseableHttpResponse response = post(null); assertEquals(400, response.getStatusLine().getStatusCode()); String bodyAsString = EntityUtils.toString(response.getEntity()); assertThat(bodyAsString, startsWith("{\"error\":{\"message\":\"SQLActionException[missing request body]\"," + "\"code\":4000},\"error_trace\":\"SQLActionException:")); }
From source file:password.pwm.ws.client.rest.RestClientHelper.java
public static String makeOutboundRestWSCall(final PwmApplication pwmApplication, final Locale locale, final String url, final String jsonRequestBody) throws PwmOperationalException, PwmUnrecoverableException { final HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue()); if (locale != null) { httpPost.setHeader("Accept-Locale", locale.toString()); }/*from ww w. j a va2s . c om*/ httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue()); final HttpResponse httpResponse; try { final StringEntity stringEntity = new StringEntity(jsonRequestBody); stringEntity.setContentType(PwmConstants.AcceptValue.json.getHeaderValue()); httpPost.setEntity(stringEntity); LOGGER.debug("beginning external rest call to: " + httpPost.toString() + ", body: " + jsonRequestBody); httpResponse = PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost); final String responseBody = EntityUtils.toString(httpResponse.getEntity()); LOGGER.trace("external rest call returned: " + httpResponse.getStatusLine().toString() + ", body: " + responseBody); if (httpResponse.getStatusLine().getStatusCode() != 200) { final String errorMsg = "received non-200 response code (" + httpResponse.getStatusLine().getStatusCode() + ") when executing web-service"; LOGGER.error(errorMsg); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg)); } return responseBody; } catch (IOException e) { final String errorMsg = "http response error while executing external rest call, error: " + e.getMessage(); LOGGER.error(errorMsg); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg), e); } }
From source file:cn.org.once.cstack.maven.plugin.handler.ResponseErrorHandler.java
@Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else {/*w ww. j av a2 s .c o m*/ switch (status) { case 500: InputStreamReader reader = null; reader = new InputStreamReader(response.getEntity().getContent()); LineIterator lineIterator = new LineIterator(reader); StringBuilder jsonStringBuilder = new StringBuilder(); while (lineIterator.hasNext()) { jsonStringBuilder.append(lineIterator.nextLine()); } throw new ClientProtocolException(jsonStringBuilder.toString()); case 401: throw new ClientProtocolException("Status 401 - Bad credentials!"); case 403: throw new ClientProtocolException("Status 403 - You must be an admin to execute this command!"); case 404: throw new ClientProtocolException( "Status 404 - The server can treat the request, please contact an admin"); default: throw new ClientProtocolException("Cloudunit server does not response. Please contact an admin"); } } }
From source file:com.lambdasoup.panda.PandaHttp.java
static String get(String url, Map<String, String> params, Properties properties) { Map<String, String> sParams = signedParams("GET", url, params, properties); String flattenParams = canonicalQueryString(sParams); String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams; HttpGet httpGet = new HttpGet(requestUrl); DefaultHttpClient httpclient = new DefaultHttpClient(); String stringResponse = null; try {//from w ww . j ava2 s.c o m HttpResponse response = httpclient.execute(httpGet); stringResponse = EntityUtils.toString(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } return stringResponse; }
From source file:org.jetbrains.teamcity.widgets.JsonResponseHelper.java
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { DefaultHttpClient client = new DefaultHttpClient(); String url = servletRequest.getParameter("url"); //HttpGet httpget = new HttpGet("http://buildserver/guestAuth/app/rest/investigations?locator=state:TAKEN"); HttpGet httpget = new HttpGet("http://buildserver/" + url); httpget.setHeader("Accept", "application/json"); HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); servletResponse.getWriter().write(EntityUtils.toString(entity)); }
From source file:uk.gov.hmrc.service.ServiceConnector.java
public String get(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException { HttpGet request = new HttpGet(url); request.addHeader("Accept", acceptHeader); if (bearerToken.isPresent()) { request.addHeader("Authorization", "Bearer " + bearerToken.get()); }// w ww .ja v a2 s . com try { HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 401) { throw new UnauthorizedException(); } return EntityUtils.toString(response.getEntity()); } catch (IOException e) { throw new RuntimeException(e); } }