List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:org.earthtime.archivingTools.IEDACredentialsValidator.java
private static Document HTTP_PostAndResponse(String userName, String password, String credentialsService) { Document doc = null;/*w w w . j a v a 2s . co m*/ Map<String, String> dataToPost = new HashMap<>(); dataToPost.put("username", userName); dataToPost.put("password", password); CloseableHttpClient httpclient = HttpClients.createDefault(); org.apache.http.client.methods.HttpPost httpPost = new HttpPost(credentialsService); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); CloseableHttpResponse httpResponse = null; try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpResponse = httpclient.execute(httpPost); HttpEntity myEntity = httpResponse.getEntity(); InputStream response = myEntity.getContent(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); try { doc = factory.newDocumentBuilder().parse(response); //System.out.println("CCCC" + doc.getElementsByTagName("valid").item(0).getTextContent().trim()); } catch (ParserConfigurationException | SAXException | IOException parserConfigurationException) { System.out.println("PARSE error " + parserConfigurationException.getMessage()); } EntityUtils.consume(myEntity); } catch (IOException iOException) { } finally { try { httpResponse.close(); } catch (IOException iOException) { } } return doc; }
From source file:org.smartloli.kafka.eagle.common.util.HttpClientUtils.java
/** * Send request by get method./*from w w w.j av a 2 s.c o m*/ * * @param uri: * http://ip:port/demo?httpcode=200&name=smartloli */ public static String doGet(String uri) { String result = ""; try { CloseableHttpClient client = null; CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(uri); client = HttpClients.createDefault(); response = client.execute(httpGet); HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity); } finally { if (response != null) { response.close(); } if (client != null) { client.close(); } } } catch (Exception e) { e.printStackTrace(); LOG.error("Do get request has error, msg is " + e.getMessage()); } return result; }
From source file:com.aws.sampleImage.url.TestHttpGetFlickrAPI.java
private static String callFlickrAPIForEachKeyword(String query) throws IOException, JSONException { String apiKey = "ad4f88ecfd53b17f93178e19703fe00d"; String apiSecret = "96cab0e9f89468d6"; int totalPages = 4; int total = 500; int perPage = 500; int counter = 0; int currentCount = 0; for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) { String url = "https://api.flickr.com/services/rest/?method=flickr.photos.search&text=" + query + "&extras=url_c,url_m,url_n,license,owner_name&per_page=500&page=" + i + "&format=json&api_key=" + apiKey + "&api_secret=" + apiSecret + "&license=4,5,6,7,8"; System.out.println("URL FORMED --> " + url); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine;//from w ww .j av a 2 s.c om StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); String responseString = response.toString(); responseString = responseString.replace("jsonFlickrApi(", ""); int length = responseString.length(); responseString = responseString.substring(0, length - 1); // print result System.out.println("After making it a valid JSON --> " + responseString); httpClient.close(); JSONObject json = null; try { json = new JSONObject(responseString); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println("Converted JSON String " + json); JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null; total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0; perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0; System.out.println(" perPage --> " + perPage + " total --> " + total); JSONArray photoArr = photosObj.getJSONArray("photo"); System.out.println("Length of Array --> " + photoArr.length()); String scrapedImageURL = ""; for (int itr = 0; itr < photoArr.length(); itr++) { JSONObject tempObject = photoArr.getJSONObject(itr); scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c") : tempObject.has("url_m") ? tempObject.getString("url_m") : tempObject.has("url_n") ? tempObject.getString("url_n") : ""; //System.out.println("Scraped Image URL --> " + scrapedImageURL); counter++; } } System.out.println("C O U N T E R -> " + counter); return null; }
From source file:de.bmarwell.j9kwsolver.util.HttpConnectorFactory.java
/** * Returns the Body from the URI via http request. * @param uri the URI to get the body from. * @return the Body as String.//from w ww .jav a 2 s . c om */ public static String getBodyFromRequest(final URI uri) { CloseableHttpResponse response = null; String responseBody = null; HttpGet httpGet = new HttpGet(uri); LOG.debug("Requesting URI: {}.", httpGet.getURI()); try { response = httpClient.execute(httpGet); StringWriter writer = new StringWriter(); IOUtils.copy(response.getEntity().getContent(), writer); responseBody = writer.toString(); } catch (IOException e) { LOG.error("Fehler beim HTTP Request!", e); } return responseBody; }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
/** * HTTPS//from w ww. j a v a2 s. c om * * @param url * @param params * @return */ public static String post(String url, Map<String, String> params, int connectTimeout, Charset charset) { final HttpPost httpPost = new HttpPost(url); httpPost.setConfig(buildConfig(connectTimeout, connectTimeout)); try { setParam(httpPost, params, charset); final CloseableHttpResponse response = httpClient.execute(httpPost); try { // POST final HttpEntity entity = response.getEntity(); // ?? if (null != entity) return EntityUtils.toString(entity, charset); } catch (Exception e) { logger.error("[HttpUtils Post] get response error, url:" + url, e); } finally { if (response != null) response.close(); } } catch (ClientProtocolException e) { logger.error("[HttpUtils Post] invoke timeout, url=" + url, e); } catch (Exception e) { logger.error("[HttpUtils Post] invoke error, url=" + url, e); } finally { httpPost.releaseConnection(); } return null; }
From source file:nl.knaw.dans.easy.sword2examples.ContinuedDeposit.java
public static URI depositPackage(File bagDir, IRI colIri, String uid, String pw, int chunkSize) throws Exception { // 0. Zip the bagDir File zipFile = new File(bagDir.getAbsolutePath() + ".zip"); zipFile.delete();/* w ww.j av a 2 s . co m*/ Common.zipDirectory(bagDir, zipFile); // 1. Set up stream for calculating MD5 FileInputStream fis = new FileInputStream(zipFile); MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(fis, md); // 2. Post first chunk bag to Col-IRI CloseableHttpClient http = Common.createHttpClient(colIri.toURI(), uid, pw); CloseableHttpResponse response = Common.sendChunk(dis, chunkSize, "POST", colIri.toURI(), "bag.zip.1", "application/octet-stream", http, chunkSize < zipFile.length()); // 3. Check the response. If transfer corrupt (MD5 doesn't check out), report and exit. String bodyText = Common.readEntityAsString(response.getEntity()); if (response.getStatusLine().getStatusCode() != 201) { System.err.println("FAILED. Status = " + response.getStatusLine()); System.err.println("Response body follows:"); System.err.println(bodyText); System.exit(2); } System.out.println("SUCCESS. Deposit receipt follows:"); System.out.println(bodyText); Entry receipt = Common.parse(bodyText); Link seIriLink = receipt.getLink("edit"); URI seIri = seIriLink.getHref().toURI(); int remaining = (int) zipFile.length() - chunkSize; int count = 2; while (remaining > 0) { System.out.print(String.format("POST-ing chunk of %d bytes to SE-IRI (remaining: %d) ... ", chunkSize, remaining)); response = Common.sendChunk(dis, chunkSize, "POST", seIri, "bag.zip." + count++, "application/octet-stream", http, remaining > chunkSize); remaining -= chunkSize; bodyText = Common.readEntityAsString(response.getEntity()); if (response.getStatusLine().getStatusCode() != 200) { System.err.println("FAILED. Status = " + response.getStatusLine()); System.err.println("Response body follows:"); System.err.println(bodyText); System.exit(2); } System.out.println("SUCCESS."); } // 4. Get the statement URL. This is the URL from which to retrieve the current status of the deposit. System.out.println("Retrieving Statement IRI (Stat-IRI) from deposit receipt ..."); receipt = Common.parse(bodyText); Link statIriLink = receipt.getLink("http://purl.org/net/sword/terms/statement"); IRI statIri = statIriLink.getHref(); System.out.println("Stat-IRI = " + statIri); // 5. Check statement every ten seconds (a bit too frantic, but okay for this test). If status changes: // report new status. If status is an error (INVALID, REJECTED, FAILED) or ARCHIVED: exit. return Common.trackDeposit(http, statIri.toURI()); }
From source file:utils.TestUtils.java
public static String httpGet(String url) throws Exception { CloseableHttpResponse resp = null; try {//from w w w. ja v a2 s . co m HttpGet get = new HttpGet(url); resp = HTTP.execute(get); return EntityUtils.toString(resp.getEntity(), "UTF-8"); } finally { closeQuietly(resp); } }
From source file:com.networknt.light.server.handler.loader.PageLoader.java
private static void loadPageFile(String host, File file) { Scanner scan = null;/*from www . j a va 2 s. c o m*/ try { scan = new Scanner(file, Loader.encoding); // the content is only the data portion. convert to map String content = scan.useDelimiter("\\Z").next(); String pageId = file.getName(); pageId = pageId.substring(0, pageId.lastIndexOf('.')); if (content != null && !content.equals(pageMap.get(pageId))) { System.out.println(content); System.out.println(pageMap.get(pageId)); Map<String, Object> inputMap = new HashMap<String, Object>(); inputMap.put("category", "page"); inputMap.put("name", "impPage"); inputMap.put("readOnly", false); Map<String, Object> data = new HashMap<String, Object>(); data.put("pageId", pageId); data.put("content", content); inputMap.put("data", data); HttpPost httpPost = new HttpPost(host + "/api/rs"); httpPost.addHeader("Authorization", "Bearer " + jwt); StringEntity input = new StringEntity( ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap)); input.setContentType("application/json"); httpPost.setEntity(input); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println("Page: " + file.getAbsolutePath() + " is loaded with status " + 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(); } } else { //System.out.println("Skip file " + pageId); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (scan != null) scan.close(); } }
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);/*from www . j ava2 s .co m*/ data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }
From source file:org.drftpd.util.HttpUtils.java
public static String retrieveHttpAsString(String url) throws HttpException, IOException { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000) .setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig) .setUserAgent(_userAgent).build(); HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig);/*from w w w . j ava 2 s .c o m*/ CloseableHttpResponse response = null; try { response = httpclient.execute(httpGet); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new HttpException("Error " + statusCode + " for URL " + url); } HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); EntityUtils.consume(entity); return data; } catch (IOException e) { throw new IOException("Error for URL " + url, e); } finally { if (response != null) { response.close(); } httpclient.close(); } }