List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:org.wuspba.ctams.ws.ITBandResultController.java
private static void add() throws Exception { ITBandController.add();//from w w w . j a va 2 s .co m ITBandContestController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getBands().add(TestFixture.INSTANCE.skye); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getResults().add(TestFixture.INSTANCE.result1); doc.getResults().add(TestFixture.INSTANCE.result2); doc.getResults().add(TestFixture.INSTANCE.result3); doc.getResults().add(TestFixture.INSTANCE.result4); doc.getBandContests().add(TestFixture.INSTANCE.bandContest); doc.getBandContestResults().add(TestFixture.INSTANCE.bandResult); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.bandResult.setId(doc.getBandContestResults().get(0).getId()); for (Result r : doc.getBandContestResults().get(0).getResults()) { if (r.getPoints() == TestFixture.INSTANCE.result1.getPoints()) { TestFixture.INSTANCE.result1.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result2.getPoints()) { TestFixture.INSTANCE.result2.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result3.getPoints()) { TestFixture.INSTANCE.result3.setId(r.getId()); } else if (r.getPoints() == TestFixture.INSTANCE.result4.getPoints()) { TestFixture.INSTANCE.result4.setId(r.getId()); } } 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); } } } }
From source file:com.bacic5i5j.framework.toolbox.web.WebUtils.java
/** * ??//from w ww. j av a 2 s .c o m * * @param params * @param url * @return */ public static String post(Map<String, String> params, String url) { String result = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = generateURLParams(params); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException e) { log.error(e.getMessage() + " : " + e.getCause()); } CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); } catch (IOException e) { log.error(e.getMessage() + " : " + e.getCause()); } if (response != null) { StatusLine statusLine = response.getStatusLine(); log.info("??: " + statusLine.getStatusCode()); if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) { try { InputStream is = response.getEntity().getContent(); int count = is.available(); byte[] buffer = new byte[count]; is.read(buffer); result = new String(buffer); } catch (IOException e) { log.error("???: " + e.getMessage()); } } } return result; }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java
private static CloseableHttpClient recordHttpClientForMultipleJsonAndStatusCodeResponse( List<String> jsonResponses, List<Integer> statusCodes) throws IOException { CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class); List<HttpEntity> httpEntities = jsonResponses.stream() .map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList()); when(httpResponseMock.getEntity()).thenReturn(httpEntities.get(0), httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1])); List<StatusLine> statusLines = statusCodes.stream().map(ConfluenceRestClientTest::recordStatusLine) .collect(toList());//from www . j a v a 2s . c o m when(httpResponseMock.getStatusLine()).thenReturn(statusLines.get(0), statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1])); CloseableHttpClient httpClientMock = anyCloseableHttpClient(); when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock); return httpClientMock; }
From source file:org.darkware.wpman.wpcli.WPCLI.java
/** * Update the local WP-CLI tool to the most recent version. *//* ww w . j av a 2s . com*/ public static void update() { try { WPManager.log.info("Downloading new version of WP-CLI."); CloseableHttpClient httpclient = HttpClients.createDefault(); URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com") .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build(); WPManager.log.info("Downloading from: {}", pharURI); HttpGet downloadRequest = new HttpGet(pharURI); CloseableHttpResponse response = httpclient.execute(downloadRequest); WPManager.log.info("Download response: {}", response.getStatusLine()); WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue()); FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); response.getEntity().writeTo(Channels.newOutputStream(wpcliFile)); wpcliFile.close(); Set<PosixFilePermission> wpcliPerms = new HashSet<>(); wpcliPerms.add(PosixFilePermission.OWNER_READ); wpcliPerms.add(PosixFilePermission.OWNER_WRITE); wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE); wpcliPerms.add(PosixFilePermission.GROUP_READ); wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms); } catch (URISyntaxException e) { WPManager.log.error("Failure building URL for WPCLI download.", e); System.exit(1); } catch (IOException e) { WPManager.log.error("Error while downloading WPCLI client.", e); e.printStackTrace(); System.exit(1); } }
From source file:com.frochr123.helper.CachedFileDownloader.java
public static SimpleEntry<String, ByteArrayOutputStream> getResultFromURL(String url) throws IOException { SimpleEntry<String, ByteArrayOutputStream> result = null; String finalUrl = null;// w w w . j a v a2s. co m ByteArrayOutputStream outputStream = null; if (url == null || url.isEmpty()) { return null; } // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT) .setConnectTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT) .setConnectionRequestTimeout(CACHE_DOWNLOADER_DEFAULT_TIMEOUT).build(); // Create HTTP Get request HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); // Create context HttpContext context = new BasicHttpContext(); // Check for temporary FabQR download of own configured private FabQR instance // In that case Authorization needs to be added if (FabQRFunctions.getFabqrPrivateURL() != null && !FabQRFunctions.getFabqrPrivateURL().isEmpty() && url.startsWith(FabQRFunctions.getFabqrPrivateURL()) && url.contains("/" + FabQRFunctions.FABQR_TEMPORARY_MARKER + "/")) { // Set authentication information String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(), FabQRFunctions.getFabqrPrivatePassword()); if (!encodedCredentials.isEmpty()) { httpGet.addHeader("Authorization", "Basic " + encodedCredentials); } } // Send request CloseableHttpResponse response = httpClient.execute(httpGet, context); // Get all redirected locations from context, if there are any RedirectLocations redirectLocations = (RedirectLocations) (context .getAttribute(HttpClientContext.REDIRECT_LOCATIONS)); if (redirectLocations != null) { finalUrl = redirectLocations.getAll().get(redirectLocations.getAll().size() - 1).toString(); } else { finalUrl = url; } // Check response valid and max file size if (response.getEntity() == null || response.getEntity().getContentLength() > CACHE_DOWNLOADER_MAX_FILESIZE_BYTES) { return null; } // Get data outputStream = new ByteArrayOutputStream(); response.getEntity().writeTo(outputStream); // Return result result = new SimpleEntry<String, ByteArrayOutputStream>(finalUrl, outputStream); return result; }
From source file:org.jivesoftware.openfire.MessageRouter.java
/** * Http Post ?//from www . j av a 2 s. c o m * @param url url? * @param paras ?? * @return String : * */ public static String httpPost(String url, Map<String, String> paras) { //? String resultStr = null; try { //httpClient CloseableHttpClient httpClient = HttpClients.createDefault(); //???? List<NameValuePair> formParas = new ArrayList<NameValuePair>(); if (paras != null) { for (String key : paras.keySet()) { formParas.add(new BasicNameValuePair(key, paras.get(key))); } } //??? UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParas, ENCODING); //?post HttpPost httpPost = new HttpPost(url); //post httpPost.setEntity(entity); //?HttpResponse CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { // HttpEntity httpEntity = httpResponse.getEntity(); //? if (httpEntity != null) { //,??? InputStream inputStream = httpEntity.getContent(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, length); } byte[] result = bos.toByteArray(); //??? resultStr = new String(result, ENCODING); System.out.println(resultStr); } catch (Exception e) { System.out.println(e.getMessage()); } finally { //? inputStream.close(); } } } catch (Exception e) { System.out.println(e.getMessage()); } finally { httpResponse.close(); } } catch (Exception e) { System.out.println(e.getMessage()); } return resultStr; }
From source file:com.flurry.proguard.UploadMapping.java
/** * Ensure that a response had an expected status * * @param response the API response/* w w w .j ava2 s . c o m*/ * @param validStatuses the list of acceptable statuses */ private static void expectStatus(CloseableHttpResponse response, Integer... validStatuses) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { failWithError("The provided token is expired"); } if (!Arrays.asList(validStatuses).contains(statusCode)) { String responseString; try { responseString = "Response Body: " + EntityUtils.toString(response.getEntity()); } catch (IOException e) { responseString = "IO Exception while reading the response body."; } failWithError("Request failed: {} {}", statusCode, responseString); } }
From source file:com.zxy.commons.httpclient.HttpclientUtils.java
/** * Get url//from w w w . j a v a 2s. co m * * @param connectTimeoutSec () * @param socketTimeoutSec ??() * @param url url? * @return post?? * @throws ClientProtocolException ClientProtocolException * @throws IOException IOException */ public static String get(int connectTimeoutSec, int socketTimeoutSec, String url) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { // httpClient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000) .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000) .build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, Charsets.UTF_8); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:eu.diacron.crawlservice.app.Util.java
public static String getCrawlid(URL urltoCrawl) { String crawlid = ""; System.out.println("start crawling page"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(Configuration.REMOTE_CRAWLER_USERNAME, Configuration.REMOTE_CRAWLER_PASS)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {//from w ww.j a v a2 s . c o m //HttpPost httppost = new HttpPost("http://diachron.hanzoarchives.com/crawl"); HttpPost httppost = new HttpPost(Configuration.REMOTE_CRAWLER_URL_CRAWL_INIT); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("name", UUID.randomUUID().toString())); urlParameters.add(new BasicNameValuePair("scope", "page")); urlParameters.add(new BasicNameValuePair("seed", urltoCrawl.toString())); httppost.setEntity(new UrlEncodedFormEntity(urlParameters)); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { crawlid = inputLine; } in.close(); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex); } } return crawlid; }
From source file:com.ibm.watson.movieapp.dialog.rest.UtilityFunctions.java
/** * Parses response to JSON object/*from www. ja v a 2s . com*/ * <p> * This extracts a JSON object response from a CloseableHttpResponse.</p> * * @param response the CloseableHttpResponse * @return the JSON object response * @throws IllegalStateException if the response stream cannot be parsed correctly * @throws IOException if it is unable to parse the response * @throws HttpException if the HTTP call responded with a status code other than 200 or 201 */ public static JsonObject parseHTTPResponse(CloseableHttpResponse response, String uri) throws IllegalStateException, IOException, HttpException { int statusCode = response.getStatusLine().getStatusCode(); // Messages.setInfo(response.getLocale()); if (statusCode != 200 && statusCode != 201) { logger.error(MessageFormat.format(Messages.getString("UtilityFunctions.HTTP_STATUS"), //$NON-NLS-1$ response.getStatusLine().getStatusCode(), uri)); throw new HttpException(MessageFormat.format(Messages.getString("UtilityFunctions.HTTP_STATUS"), response.getStatusLine().getStatusCode(), uri)); } HttpEntity entity = response.getEntity(); String strResponse = EntityUtils.toString(entity); JsonElement je = new JsonParser().parse(strResponse); JsonObject jo = je.getAsJsonObject(); return jo; }