List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity
HttpEntity getEntity();
From source file:PinotResponseTime.java
private static boolean isValid(CloseableHttpResponse res, String path) throws Exception { if (res.getStatusLine().getStatusCode() != 200) { return false; }//from ww w. j av a2 s . c o m String response = ""; int length; try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) { while ((length = in.read(BUFFER)) > 0) { response += new String(BUFFER, 0, length, "UTF-8"); } } if (response.contains("\"numDocsScanned\":0")) { return false; } if (path != null) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, false))) { writer.write(response); } } return true; }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
public static byte[] getBytes(String url, Map<String, String> params, int connectTimeout) { final String uri = setParam(url, params, Consts.UTF_8); final HttpGet get = new HttpGet(uri); get.setConfig(buildConfig(connectTimeout, connectTimeout)); try {/*from ww w.j av a 2s . c om*/ final CloseableHttpResponse response = httpClient.execute(get); try { final HttpEntity entity = response.getEntity(); if (entity.getContentLength() > 0) return EntityUtils.toByteArray(entity); logger.error("[HttpUtils Get]get content error,content=" + EntityUtils.toString(entity)); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]get response error, url:%s", uri), e); } finally { if (response != null) response.close(); } } catch (SocketTimeoutException e) { logger.error(String.format("[HttpUtils Get]invoke get timeout error, url:%s", uri), e); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]invoke get error, url:%s", uri), e); } finally { get.releaseConnection(); } return null; }
From source file:erainformatica.utility.JSONHelper.java
public static TelegramRequestResult<JSONObject> readJsonFromUrl(String url, InputFile file) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); builder.addBinaryBody(file.getName(), file.getFile_content(), ContentType.APPLICATION_OCTET_STREAM, file.getName() + "." + file.getExtension()); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart);/*from ww w. j av a 2 s .c o m*/ CloseableHttpResponse response = null; try { response = httpClient.execute(uploadFile); } catch (IOException ex) { Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex); } HttpEntity responseEntity = response.getEntity(); try { return readJsonFromInputStream(responseEntity.getContent()); } catch (Exception ex) { return new TelegramRequestResult<>(false, ex.toString(), null); } }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
/** * http get// w ww . j av a2 s . co m * * @param url * @param params * @param connectTimeout * @return */ public static String get(String url, Map<String, String> params, int connectTimeout, Charset charset) { final String uri = setParam(url, params, charset); final HttpGet get = new HttpGet(uri); get.setConfig(buildConfig(connectTimeout, connectTimeout)); try { final CloseableHttpResponse response = httpClient.execute(get); try { final HttpEntity entity = response.getEntity(); if (entity != null) return EntityUtils.toString(entity, charset); } catch (Exception e) { logger.error(String.format("[HttpUtils Get] get response error, url:%s", uri), e); } finally { if (response != null) response.close(); } } catch (SocketTimeoutException e) { logger.error(String.format("[HttpUtils Get] invoke timeout error, url:%s", uri)); } catch (SocketException e) { logger.error(String.format("[HttpUtils Get] invoke connection refused, url:%s", uri)); } catch (Exception e) { logger.error(String.format("[HttpUtils Get] invoke error, url:%s", uri), e); } finally { get.releaseConnection(); } return null; }
From source file:org.rapidoid.http.HTTP.java
public static byte[] get(String uri) { try {//from www. j a v a2s . c o m CloseableHttpClient client = client(uri); HttpGet get = new HttpGet(uri); Log.info("Starting HTTP GET request", "request", get.getRequestLine()); CloseableHttpResponse response = client.execute(get); 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); } catch (Throwable e) { throw U.rte(e); } }
From source file:nl.knaw.dans.easy.sword2examples.SimpleDeposit.java
public static URI depositPackage(File bagDir, IRI colIri, String uid, String pw) throws Exception { // 0. Zip the bagDir File zipFile = new File(bagDir.getAbsolutePath() + ".zip"); zipFile.delete();/* w w w. j a v a2s . co m*/ Common.zipDirectory(bagDir, zipFile); // 1. Set up stream for calculating MD5 MessageDigest md = MessageDigest.getInstance("MD5"); try (FileInputStream fis = new FileInputStream(zipFile); DigestInputStream dis = new DigestInputStream(fis, md)) { // 2. Post entire bag to Col-IRI CloseableHttpClient http = Common.createHttpClient(colIri.toURI(), uid, pw); CloseableHttpResponse response = Common.sendChunk(dis, (int) zipFile.length(), "POST", colIri.toURI(), "bag.zip", "application/zip", http, false); // 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); // 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 ..."); Entry receipt = Common.parse(bodyText); Link statLink = receipt.getLink("http://purl.org/net/sword/terms/statement"); IRI statIri = statLink.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:org.sead.repositories.reference.util.SEADAuthenticator.java
static public HttpClientContext authenticate(String server) { boolean authenticated = false; log.info("Authenticating"); String accessToken = SEADGoogleLogin.getAccessToken(); // Now login to server and create a session CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w. j a va 2 s .co m // //DoLogin is the auth endpoint when using the AUthFilter, versus // the api/authenticate endpoint when connecting to the ACR directly HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin"); List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1); nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken)); seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList)); CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // String seadSessionId = // EntityUtils.toString(resEntity); authenticated = true; } } else { // Seems to occur when google device id is not set on server // - with a Not Found response... log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Cannot read sead-google.json"); log.error(e.getMessage()); } // localContext should have the cookie with the SEAD session key, which // nominally is all that's needed. // FixMe: If there is no activity for more than 15 minutes, the session // may expire, in which case, // re-authentication using the refresh token to get a new google token // to allow SEAD login again may be required // also need to watch the 60 minutes google token timeout - project // spaces will invalidate the session at 60 minutes even if there is // activity authTime = System.currentTimeMillis(); if (authenticated) { return localContext; } return null; }
From source file:com.oakhole.voa.utils.HttpClientUtils.java
public static String post(String uri, File file) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(uri); try {/*from w w w. j a v a 2 s. c om*/ InputStreamEntity inputStreamEntity = new InputStreamEntity(new FileInputStream(file)); //???? httpPost.setEntity(inputStreamEntity); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); return EntityUtils.toString(httpResponse.getEntity()); } catch (IOException e) { logger.error(":{}", e.getMessage()); } } catch (FileNotFoundException e) { logger.error(":{}", e.getMessage()); } return ""; }
From source file:lh.api.showcase.server.util.HttpQueryUtils.java
public static String executeQuery(URI uri, ApiAuth apiAuth, HasProxySettings proxySetting, HttpClientFactory httpClientFactory, final int maxRetries) throws HttpErrorResponseException { //logger.info("uri: " + uri.toString()); AtomicInteger tryCounter = new AtomicInteger(0); while (true) { CloseableHttpClient httpclient = httpClientFactory.getHttpClient(proxySetting); HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("Authorization", apiAuth.getAuthHeader()); httpGet.addHeader("Accept", "application/json"); //logger.info("auth: " + apiAuth.getAuthHeader()) ; //logger.info("query: " + httpGet.toString()); CloseableHttpResponse response = null; try {//from www . jav a2 s. c o m response = httpclient.execute(httpGet); StatusLine status = response.getStatusLine(); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); String json = IOUtils.toString(entity.getContent(), "UTF8"); EntityUtils.consume(entity); //logger.info("response: " + json); // check for errors if (status != null && status.getStatusCode() > 299) { if (status.getStatusCode() == 401) { // token has probably expired logger.info("Authentication Error. Token will be refreshed"); if (tryCounter.getAndIncrement() < maxRetries) { if (apiAuth.updateAccessToken()) { logger.info("Token successfully refreshed"); // we retry with the new token logger.info("Retry number " + tryCounter.get()); continue; } } } throw new HttpErrorResponseException(status.getStatusCode(), status.getReasonPhrase(), json); } return json; } catch (IOException e) { logger.severe(e.getMessage()); break; } finally { try { if (response != null) { response.close(); } } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage()); } } } return null; }
From source file:cn.mrdear.pay.util.WebUtils.java
/** * ?,//from www. ja v a 2s . c om * @param httpResponse ?? * @return */ private static String consumeResponse(CloseableHttpResponse httpResponse) { String result = null; try { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { result = EntityUtils.toString(httpEntity, "UTF-8"); EntityUtils.consume(httpEntity); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpResponse.close(); } catch (IOException ignored) { } } return result; }