List of usage examples for org.apache.http.entity BufferedHttpEntity BufferedHttpEntity
public BufferedHttpEntity(HttpEntity httpEntity) throws IOException
From source file:com.mike.aframe.http.HttpCallBack.java
void sendResponseMessage(String uri, HttpConfig config, HttpResponse response) { StatusLine status = response.getStatusLine(); String responseBody = null;//from w w w . ja v a2s . co m try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, "UTF-8"); } } catch (IOException e) { sendFailureMessage(e, (String) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { if (config.isUseCache()) { config.getCacher().add(uri, responseBody); } sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } }
From source file:org.elasticsearch.client.RequestLogger.java
/** * Creates curl output for given request *//*from w ww.j av a 2 s. c o m*/ static String buildTraceRequest(HttpUriRequest request, HttpHost host) throws IOException { String requestLine = "curl -iX " + request.getMethod() + " '" + host + getUri(request.getRequestLine()) + "'"; if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; if (enclosingRequest.getEntity() != null) { requestLine += " -d '"; HttpEntity entity = enclosingRequest.getEntity(); if (entity.isRepeatable() == false) { entity = new BufferedHttpEntity(enclosingRequest.getEntity()); enclosingRequest.setEntity(entity); } requestLine += EntityUtils.toString(entity, StandardCharsets.UTF_8) + "'"; } } return requestLine; }
From source file:io.uploader.drive.drive.largefile.DriveAuth.java
public boolean updateAccessToken() throws UnsupportedEncodingException, IOException { // If a refresh_token is set, this class tries to retrieve an access_token. // If refresh_token is no longer valid it resets all tokens to an empty string. if (refreshToken.isEmpty() || accessToken.isEmpty()) { accessToken = config.getCredential().getAccessToken(); tokenType = ""; refreshToken = config.getCredential().getRefreshToken(); }/* w ww.j a v a 2 s .c om*/ logger.info("Updating access_token from Google"); CloseableHttpClient httpclient = getHttpClient(); HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("client_id", clientId)); nvps.add(new BasicNameValuePair("client_secret", clientSecret)); nvps.add(new BasicNameValuePair("refresh_token", refreshToken)); nvps.add(new BasicNameValuePair("grant_type", "refresh_token")); BufferedHttpEntity postentity = new BufferedHttpEntity(new UrlEncodedFormEntity(nvps)); httpPost.setEntity(postentity); CloseableHttpResponse response = httpclient.execute(httpPost); BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); boolean tokensOK = false; try { if (response.getStatusLine().getStatusCode() == 200 && entity != null) { String retSrc = EntityUtils.toString(entity); JSONObject result = new JSONObject(retSrc); accessToken = result.getString("access_token"); tokenType = result.getString("token_type"); tokensOK = true; } } finally { response.close(); } httpclient.close(); if (!tokensOK) { refreshToken = ""; accessToken = ""; tokenType = ""; } return tokensOK; }
From source file:br.com.jbugbrasil.bot.telegram.api.message.sender.MessageSender.java
/** * Prepara a request e envia a mensagem para a API do telegram para o grupo ou chat destinatrio da mensagem. * Parmetros necessrios para efetuar a request: * - chat_id = chat ou grupo/* w w w . ja va 2 s. c o m*/ * - parse_mode = default HTML, markdown h muitos problemas de formatao nos diversos clients disponveis. * - reply_to_message_id = Id de uma mensagem enviada, se presente a mensagem ser respondida ao seu remetente original * - disable_web_page_preview = desabilita pr vizualizao de links. * @param message Mensagem a ser enviada */ private void send(Message message) { ObjectMapper objectMapper = new ObjectMapper(); try { String url = String.format(TELEGRAM_API_SENDER_ENDPOINT, botTokenId); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("charset", StandardCharsets.UTF_8.name()); httpPost.addHeader("content-type", "application/json"); Map<String, String> body = new HashMap<>(); body.put("chat_id", message.getChat().getId() + ""); body.put("parse_mode", "HTML"); body.put("reply_to_message_id", message.getMessageId() + ""); body.put("text", message.getText()); body.put("disable_web_page_preview", "true"); httpPost.setEntity( new StringEntity(objectMapper.writeValueAsString(body), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpClient.get().execute(httpPost)) { HttpEntity responseEntity = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(responseEntity); String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); log.fine("Telegram API response: [" + responseContent + "]"); } catch (final Exception e) { e.printStackTrace(); log.warning("Erro encontrado " + e.getMessage()); } } catch (final Exception e) { e.printStackTrace(); log.warning("Erro encontrado " + e.getMessage()); } }
From source file:de.kp.ames.http.HttpClient.java
/** * @param url// w ww . j a v a2s . c om * @param data * @return * @throws Exception */ public Response doPost(String url, String data) throws Exception { /* * Create HttpPost */ URI uri = createUri(url); HttpPost httpPost = new HttpPost(uri); /* * Set header */ byte[] bytes = data.getBytes(); int length = bytes.length; httpPost.setHeader(CONTENT_TYPE_LABEL, JSON_CONTENT_TYPE); // httpPost.setHeader(CONTENT_LENGTH_LABEL, String.valueOf(length)); HttpEntity entity = new StringEntity(data); httpPost.setEntity(entity); /* * Execute request */ HttpResponse response = httpClient.execute(httpPost); HttpEntity httpEntity = new BufferedHttpEntity(response.getEntity()); return new Response(httpEntity.getContent(), response.getStatusLine().getStatusCode()); }
From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaHttpClientDispatch.java
/** * Checks for specific outbound response codes/content to trigger a retry or failover *///from w ww. ja v a2s . com @Override protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException { if (inboundResponse.getStatusLine().getStatusCode() == 403) { BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity()); inboundResponse.setEntity(entity); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); inboundResponse.getEntity().writeTo(outputStream); String body = new String(outputStream.toByteArray()); if (body.contains("StandbyException")) { throw new StandbyException(); } if (body.contains("SafeModeException")) { throw new SafeModeException(); } } super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse); }
From source file:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java
@Override protected void deploy(List<Binary> binaries, Run run) throws IOException { CloseableHttpClient client = null;/*from w w w . j a v a 2 s. co m*/ try { if (credentialsId == null || credentialsId.isEmpty()) { client = HttpClients.createDefault(); } else { BasicCredentialsProvider credentials = new BasicCredentialsProvider(); StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, run, Lists.<DomainRequirement>newArrayList()); credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( credentialById.getUsername(), credentialById.getPassword().getPlainText())); client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries() .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build(); } for (Binary binary : binaries) { BufferedHttpEntity entity = new BufferedHttpEntity( new InputStreamEntity(binary.getFile().open(), binary.getFile().length())); HttpPost post = new HttpPost(remoteLocation + binary.getName()); post.setEntity(entity); CloseableHttpResponse response = null; try { response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { log.fine("Deployed " + binary.getName() + " to " + remoteLocation); } else { log.warning("Cannot deploy file " + binary.getName() + ". Response from target was " + statusCode); run.setResult(Result.FAILURE); throw new IOException(response.getStatusLine().toString()); } } finally { if (response != null) { response.close(); } } } } finally { if (client != null) { client.close(); } } }
From source file:com.gistlabs.mechanize.PageRequest.java
public HttpResponse consume(final HttpClient client, final HttpRequestBase request) throws Exception { if (!wasExecuted) { this.client = client; this.request = request; if (!request.getMethod().equalsIgnoreCase(httpMethod)) throw new IllegalArgumentException( String.format("Expected %s, but was %s", httpMethod, request.getMethod())); if (request.getURI().toString().equals(uri)) { HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); BasicHttpEntity entity = new BasicHttpEntity(); if (contentLocation != null) response.addHeader(new BasicHeader("Content-Location", contentLocation)); entity.setContentEncoding(charset); entity.setContentType(this.contentType); entity.setContent(this.body); response.setEntity(new BufferedHttpEntity(entity)); assertParameters(request);//from ww w .ja v a 2 s . com assertHeaders(request); this.wasExecuted = true; return response; } else { assertEquals("URI of the next PageRequest does not match", uri, request.getURI().toString()); return null; } } else throw new UnsupportedOperationException("Request already executed"); }
From source file:org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch.java
/** * Checks for specific outbound response codes/content to trigger a retry or failover *//*from www.jav a 2 s .c o m*/ @Override protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException { if (inboundResponse.getStatusLine().getStatusCode() == 403) { BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity()); inboundResponse.setEntity(entity); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); inboundResponse.getEntity().writeTo(outputStream); String body = new String(outputStream.toByteArray()); if (body.contains("StandbyException")) { throw new StandbyException(); } if (body.contains("SafeModeException") || body.contains("RetriableException")) { throw new SafeModeException(); } } super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse); }
From source file:com.mongolduu.android.ng.misc.HttpConnector.java
private static Bitmap processBitmapEntity(HttpEntity entity) throws IOException { BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent()); bufHttpEntity.consumeContent();/*from w w w. ja va 2s . c o m*/ return bm; }