List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java
private static InputStream getInputStream(final CloseableHttpResponse response) throws IOException { final InputStream inputStream; // DK_CLD: do not forward the entity stream to Jersey if the connection has been upgraded. This prevent any // component of trying to reading it, which likely result in unexpected result or even deadlock. if (response.getEntity() == null) { inputStream = new ByteArrayInputStream(new byte[0]); } else {//w w w . j a v a 2 s. c o m final InputStream i = response.getEntity().getContent(); if (i.markSupported()) { inputStream = i; } else { inputStream = new BufferedInputStream(i, ReaderWriter.BUFFER_SIZE); } } return new FilterInputStream(inputStream) { @Override public void close() throws IOException { response.close(); super.close(); } }; }
From source file:com.webarch.common.net.http.HttpService.java
/** * //from ww w.java 2 s.c om * @param url ? * @param localPath ? * @param fileName ?? * @return null/??? */ public static String downloadFile(String url, String localPath, String fileName) { int bufferSize = 1024 * 10; String file = null; if (!localPath.endsWith(File.separator)) { localPath += File.separator; } CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { HttpGet httpGet = new HttpGet(url); response = httpclient.execute(httpGet); String fileType = "dat"; Header header = response.getLastHeader("Content-Type"); if (header != null) { String headerValue = header.getValue(); fileType = headerValue.substring(headerValue.indexOf("/") + 1, headerValue.length()); } HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); if (length <= 0) { logger.warn("???"); return file; } inputStream = entity.getContent(); file = fileName + "." + fileType; File outFile = new File(localPath); if (!outFile.exists()) { outFile.mkdirs(); } localPath += file; outFile = new File(localPath); if (!outFile.exists()) { outFile.createNewFile(); } outputStream = new FileOutputStream(outFile); byte[] buffer = new byte[bufferSize]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.close(); return file; } catch (IOException e) { logger.error("?", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { logger.error("?", e); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { logger.error("??", e); } } } return file; }
From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java
private static String getErrorMessage(HttpUriRequest request, CloseableHttpResponse response) { String controllerHost = null; String controllerVersion = null; if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) { controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue(); controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue(); }//from w w w . java 2 s . c o m StatusLine statusLine = response.getStatusLine(); String reason; try { reason = new JSONObject(EntityUtils.toString(response.getEntity())).getString("error"); } catch (Exception e) { reason = "Failed to get reason"; } String errorMessage = String.format( "Got error status code: %d (%s) with reason: \"%s\" while sending request: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase(), reason, request.getURI()); if (controllerHost != null) { errorMessage = String.format("%s to controller: %s, version: %s", errorMessage, controllerHost, controllerVersion); } return errorMessage; }
From source file:org.urbantower.j4s.example.autowired.AutowiredHandlersTest.java
@Test public void isJettyServerRunning() throws InterruptedException, IOException { HttpGet request = new HttpGet("http://localhost:9093/test/servlet"); CloseableHttpResponse response = httpclient.execute(request); String body = EntityUtils.toString(response.getEntity()); Assert.assertEquals(body, "Hello Servlet"); }
From source file:com.webarch.common.net.http.HttpService.java
/** * apache httpclient?post// ww w .j av a2s . c o m * @param url ? * @param paramsMap ?map * @return ? */ public static String doHttpClientPost(String url, Map<String, String> paramsMap) { CloseableHttpClient client = HttpClients.createDefault(); String responseText = ""; CloseableHttpResponse response = null; try { HttpPost method = new HttpPost(url); if (paramsMap != null) { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> param : paramsMap.entrySet()) { NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue()); paramList.add(pair); } method.setEntity(new UrlEncodedFormEntity(paramList, DEFAULT_CHARSET)); } response = client.execute(method); HttpEntity entity = response.getEntity(); if (entity != null) { responseText = EntityUtils.toString(entity); } } catch (Exception e) { logger.error("?HTTP?", e); } finally { try { response.close(); } catch (Exception e) { logger.error("HTTPResponse?", e); } } return responseText; }
From source file:org.wuspba.ctams.ws.ITSoloContestController.java
protected static void delete() throws Exception { String id;// w ww . ja v a 2 s. c o m CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); id = doc.getSoloContests().get(0).getId(); EntityUtils.consume(entity); } httpclient = HttpClients.createDefault(); uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).setParameter("id", id) .build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try { response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITVenueController.delete(); ITHiredJudgeController.delete(); ITJudgeController.delete(); }
From source file:com.ibm.devops.dra.AbstractDevOpsAction.java
public static String getOrgId(String token, String orgName, String environment, Boolean debug_mode) { CloseableHttpClient httpClient = HttpClients.createDefault(); String organizations_url = chooseOrganizationsUrl(environment); if (debug_mode) { LOGGER.info("GET ORG_GUID URL:" + organizations_url + orgName); }//from w w w .jav a 2 s .com try { HttpGet httpGet = new HttpGet( organizations_url + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20")); httpGet = addProxyInformation(httpGet); httpGet.setHeader("Authorization", token); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); String resStr = EntityUtils.toString(response.getEntity()); if (debug_mode) { LOGGER.info("RESPONSE FROM ORGANIZATIONS API:" + response.getStatusLine().toString()); } if (response.getStatusLine().toString().contains("200")) { // get 200 response JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); JsonObject obj = element.getAsJsonObject(); JsonArray resources = obj.getAsJsonArray("resources"); if (resources.size() > 0) { JsonObject resource = resources.get(0).getAsJsonObject(); JsonObject metadata = resource.getAsJsonObject("metadata"); if (debug_mode) { LOGGER.info("ORG_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); } return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); } else { if (debug_mode) { LOGGER.info("RETURNED NO ORGANIZATIONS."); } return null; } } else { if (debug_mode) { LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); } return null; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.ibm.devops.dra.AbstractDevOpsAction.java
public static String getSpaceId(String token, String spaceName, String environment, Boolean debug_mode) { CloseableHttpClient httpClient = HttpClients.createDefault(); String spaces_url = chooseSpacesUrl(environment); if (debug_mode) { LOGGER.info("GET SPACE_GUID URL:" + spaces_url + spaceName); }//from w w w. jav a 2 s. c o m try { HttpGet httpGet = new HttpGet( spaces_url + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20")); httpGet = addProxyInformation(httpGet); httpGet.setHeader("Authorization", token); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); String resStr = EntityUtils.toString(response.getEntity()); if (debug_mode) { LOGGER.info("RESPONSE FROM SPACES API:" + response.getStatusLine().toString()); } if (response.getStatusLine().toString().contains("200")) { // get 200 response JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); JsonObject obj = element.getAsJsonObject(); JsonArray resources = obj.getAsJsonArray("resources"); if (resources.size() > 0) { JsonObject resource = resources.get(0).getAsJsonObject(); JsonObject metadata = resource.getAsJsonObject("metadata"); if (debug_mode) { LOGGER.info("SPACE_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); } return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); } else { if (debug_mode) { LOGGER.info("RETURNED NO SPACES."); } return null; } } else { if (debug_mode) { LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); } return null; } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java
public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request, Credentials credentials) throws HttpRequestException { LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request); CloseableHttpResponse response; request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0")); request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpAuthorization.authorize(request, credentials); // use defaults: 3 retries, 2 second wait between attempts RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy(); while (retryStrategy.shouldRetry()) { try {/*from ww w .j a v a2s .co m*/ response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String responseText = statusLine.getReasonPhrase(); if (responseEntity != null) { responseText = parseError(EntityUtils.toString(responseEntity)); LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText); } throw new HttpResponseException(statusLine.getStatusCode(), responseText); } if (responseEntity == null) { throw new ClientProtocolException("Response contains no content"); } return response; // don't close response yet, it is not consumed! } // if we didn't get a response at all, try again catch (NoHttpResponseException nhre) { LOGGER.warn("Thread: {}, No response from server: Retrying in {} milliseconds, retries left: {}", Thread.currentThread().getId(), retryStrategy.getTimeToWait(), retryStrategy.numberOfTriesLeft); retryStrategy.errorOccurred(); } catch (RetryException re) { throw new HttpRequestException(request, re); } catch (ClientProtocolException uhe) { throw new ConnectionException(request.getURI().toString(), uhe); } catch (IOException ioe) { throw new HttpRequestException(request, ioe); } // here we catch any exception we throw above (plus any we didn't throw ourselves), // log the problem, close any connection held by the request // and then rethrow the exception to the caller. catch (Exception exception) { LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(), exception.getCause().getLocalizedMessage()); request.releaseConnection(); throw exception; } } throw new RuntimeException("Fatal Exception: Should not have occurred!"); }
From source file:com.ibm.devops.dra.AbstractDevOpsAction.java
public static String getAppId(String token, String appName, String orgName, String spaceName, String environment, Boolean debug_mode) { CloseableHttpClient httpClient = HttpClients.createDefault(); String apps_url = chooseAppsUrl(environment); if (debug_mode) { LOGGER.info("GET APPS_GUID URL:" + apps_url + appName + ORG + orgName + SPACE + spaceName); }/*from www.ja v a 2 s . co m*/ try { HttpGet httpGet = new HttpGet(apps_url + URLEncoder.encode(appName, "UTF-8").replaceAll("\\+", "%20") + ORG + URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20") + SPACE + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20")); httpGet = addProxyInformation(httpGet); httpGet.setHeader("Authorization", token); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); String resStr = EntityUtils.toString(response.getEntity()); if (debug_mode) { LOGGER.info("RESPONSE FROM APPS API:" + response.getStatusLine().toString()); } if (response.getStatusLine().toString().contains("200")) { // get 200 response JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); JsonObject obj = element.getAsJsonObject(); JsonArray resources = obj.getAsJsonArray("resources"); if (resources.size() > 0) { JsonObject resource = resources.get(0).getAsJsonObject(); JsonObject metadata = resource.getAsJsonObject("metadata"); if (debug_mode) { LOGGER.info("APP_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", "")); } return String.valueOf(metadata.get("guid")).replaceAll("\"", ""); } else { if (debug_mode) { LOGGER.info("RETURNED NO APPS."); } return null; } } else { if (debug_mode) { LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); } return null; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }