org.apache.http.entity.BufferedHttpEntity Java Examples

The following examples show how to use org.apache.http.entity.BufferedHttpEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheHttpClientEdgeGridRequestSigner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
private byte[] serializeContent(HttpRequest request) {
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return new byte[]{};
    }

    final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request;
    HttpEntity entity = entityWithRequest.getEntity();
    if (entity == null) {
        return new byte[]{};
    }

    try {
        // Buffer non-repeatable entities
        if (!entity.isRepeatable()) {
            entityWithRequest.setEntity(new BufferedHttpEntity(entity));
        }
        return EntityUtils.toByteArray(entityWithRequest.getEntity());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: AbstractHdfsHaDispatch.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
  * Checks for specific outbound response codes/content to trigger a retry or failover
  */
@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(), StandardCharsets.UTF_8);
       if (body.contains("StandbyException")) {
          throw new StandbyException();
       }
       if (body.contains("SafeModeException") || body.contains("RetriableException")) {
          throw new SafeModeException();
       }
    }
    super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
 }
 
Example #3
Source File: RMHaBaseDispatcher.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 * Checks for specific outbound response codes/content to trigger a retry or failover
 */
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
   int status = inboundResponse.getStatusLine().getStatusCode();
   if ( status  == 403 || status == 307) {
      BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
      inboundResponse.setEntity(entity);
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      inboundResponse.getEntity().writeTo(outputStream);
      String body = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
      if (body.contains("This is standby RM")) {
         throw new StandbyException();
      }
   }
   super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}
 
Example #4
Source File: Solr6Index.java    From atlas with Apache License 2.0 6 votes vote down vote up
private void configureSolrClientsForKerberos() throws PermanentBackendException {
    String kerberosConfig = System.getProperty("java.security.auth.login.config");
    if(kerberosConfig == null) {
        throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
    }
    logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
    try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {

        SolrHttpClientBuilder kb = krbBuild.getBuilder();
        HttpClientUtil.setHttpClientBuilder(kb);
        HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                if(request instanceof HttpEntityEnclosingRequest) {
                    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
                    HttpEntity requestEntity = enclosingRequest.getEntity();
                    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
                }
            }
        };
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);

        HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
        HttpClientUtil.addRequestInterceptor(preemptiveAuth);
    }
}
 
Example #5
Source File: RequestParamEndpointTest.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
 * 
 * @since 1.3.0
 */
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
	
	Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
	
	String subpath = "/bufferedhttpentity";
	
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
	InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
	BasicHttpEntity bhe = new BasicHttpEntity();
	bhe.setContent(parallelInputStream);
	
	stubFor(put(urlEqualTo(subpath))
			.willReturn(aResponse()
			.withStatus(200)));
	
	requestEndpoint.bufferedHttpEntity(inputStream);
	
	verify(putRequestedFor(urlEqualTo(subpath))
		   .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
 
Example #6
Source File: Entities.java    From RoboZombie with Apache License 2.0 5 votes vote down vote up
/**
 * <p>Discovers the {@link HttpEntity} which is suitable for wrapping an instance of the given {@link Class}. 
 * This discovery proceeds in the following order by checking the provided generic type:</p> 
 *
 * <ol>
 * 	<li>org.apache.http.{@link HttpEntity} --&gt; returned as-is.</li> 
 * 	<li>{@code byte[]}, {@link Byte}[] --&gt; {@link ByteArrayEntity}</li> 
 *  	<li>java.io.{@link File} --&gt; {@link FileEntity}</li>
 * 	<li>java.io.{@link InputStream} --&gt; {@link BufferedHttpEntity}</li>
 * 	<li>{@link CharSequence} --&gt; {@link StringEntity}</li>
 * 	<li>java.io.{@link Serializable} --&gt; {@link SerializableEntity} (with an internal buffer)</li>
 * </ol>
 *
 * @param genericType
 * 			a generic {@link Class} to be translated to an {@link HttpEntity} type 
 * <br><br>
 * @return the {@link Class} of the translated {@link HttpEntity}
 * <br><br>
 * @throws NullPointerException
 * 			if the supplied generic type was {@code null}
 * <br><br>
 * @throws EntityResolutionFailedException
 * 			if the given generic {@link Class} failed to be translated to an {@link HttpEntity} type 
 * <br><br>
 * @since 1.3.0
 */
public static final Class<?> resolve(Class<?> genericType) {
 
 assertNotNull(genericType);
 
 try {
	 
	 Class<?> entityType = HttpEntity.class.isAssignableFrom(genericType)? HttpEntity.class :
		 				   (byte[].class.isAssignableFrom(genericType) 
					 	   || Byte[].class.isAssignableFrom(genericType))? ByteArrayEntity.class:
				 		   File.class.isAssignableFrom(genericType)? FileEntity.class :
				 		   InputStream.class.isAssignableFrom(genericType)? BufferedHttpEntity.class :
				 		   CharSequence.class.isAssignableFrom(genericType)? StringEntity.class :
				 		   Serializable.class.isAssignableFrom(genericType)? SerializableEntity.class: null;
	 
	 if(entityType == null) {
		 
		 throw new EntityResolutionFailedException(genericType);
	 }
	 
	 return entityType;
 }
 catch(Exception e) {
	 
	 throw (e instanceof EntityResolutionFailedException)? 
			 (EntityResolutionFailedException)e :new EntityResolutionFailedException(genericType, e);
 }
}
 
Example #7
Source File: HttpClientImageDownloader.java    From Roid-Library with Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    HttpGet httpRequest = new HttpGet(imageUri);
    HttpResponse response = httpClient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    return bufHttpEntity.getContent();
}
 
Example #8
Source File: HttpComponentsRamlMessage.java    From raml-tester with Apache License 2.0 5 votes vote down vote up
private BufferedHttpEntity buffered(HttpEntity entity) {
    try {
        return new BufferedHttpEntity(entity);
    } catch (IOException e) {
        throw new RamlCheckerException("Could not read content of entity", e);
    }
}
 
Example #9
Source File: SimpleResponse.java    From fanfouapp-opensource with Apache License 2.0 5 votes vote down vote up
public SimpleResponse(final HttpResponse response) {
    this.statusLine = response.getStatusLine();
    this.statusCode = this.statusLine.getStatusCode();

    final HttpEntity wrappedHttpEntity = response.getEntity();
    if (wrappedHttpEntity != null) {
        try {
            this.entity = new BufferedHttpEntity(wrappedHttpEntity);
        } catch (final IOException e) {
            this.entity = null;
        }
    }
}
 
Example #10
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city
 *
 * @return userHash to be send to use
 * @note Forecast for the following 3 days
 */
public String fetchWeatherForecastByLocation(Float longitude, Float latitude, Integer userId, String language, String units) {
    String cityFound;
    String responseToUser;
    try {
        String completURL = BASEURL + FORECASTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon="
                + URLEncoder.encode(longitude + "", "UTF-8") +
                FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);
        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
                    jsonObject.getJSONObject("city").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
            responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
                    cityFound, convertListOfForecastToString(jsonObject, language, units, true));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example #11
Source File: HttpClientImageDownloader.java    From Android-Universal-Image-Loader-Modify with Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
	HttpGet httpRequest = new HttpGet(imageUri);
	HttpResponse response = httpClient.execute(httpRequest);
	HttpEntity entity = response.getEntity();
	BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
	return bufHttpEntity.getContent();
}
 
Example #12
Source File: SdcKrb5HttpClientConfigurer.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
    IOException {
  if(request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
    HttpEntity requestEntity = enclosingRequest.getEntity();
    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
  }
}
 
Example #13
Source File: RaeService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
private List<RaeResult> fetchWord(String link, String word) {
    List<RaeResult> results = new ArrayList<>();

    String completeURL;
    try {
        completeURL = BASEURL + link;

        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completeURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        Document document = Jsoup.parse(responseString);
        Element article = document.getElementsByTag("article").first();
        String articleId = null;
        if (article != null) {
            articleId = article.attributes().get("id");
        }
        Elements elements = document.select(".j");

        if (!elements.isEmpty()) {
            results = getResultsFromExactMatch(elements, word, articleId);
        }
    } catch (IOException e) {
        BotLogger.error(LOGTAG, e);
    }

    return results;
}
 
Example #14
Source File: RaeService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
private List<RaeResult> getResultsWordSearch(String query) {
    List<RaeResult> results = new ArrayList<>();

    String completeURL;
    try {
        completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8");

        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completeURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        Document document = Jsoup.parse(responseString);
        Element list = document.select("body div ul").first();

        if (list != null) {
            Elements links = list.getElementsByTag("a");
            if (!links.isEmpty()) {
                for (Element link : links) {
                    List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), "UTF-8"), link.text());
                    if (!partialResults.isEmpty()) {
                        results.addAll(partialResults);
                    }
                }
            }
        }
    } catch (IOException e) {
        BotLogger.error(LOGTAG, e);
    }

    return results;
}
 
Example #15
Source File: RaeService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
public List<RaeResult> getResults(String query) {
    List<RaeResult> results = new ArrayList<>();

    String completeURL;
    try {
        completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8");

        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completeURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        Document document = Jsoup.parse(responseString);
        Element article = document.getElementsByTag("article").first();
        String articleId = null;
        if (article != null) {
            articleId = article.attributes().get("id");
        }
        Elements elements = document.select(".j");

        if (elements.isEmpty()) {
            results = getResultsWordSearch(query);
        } else {
            results = getResultsFromExactMatch(elements, query, articleId);
        }
    } catch (IOException e) {
        BotLogger.error(LOGTAG, e);
    }

    return results;
}
 
Example #16
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city
 *
 * @return userHash to be send to use
 * @note Forecast for the following 3 days
 */
public String fetchWeatherCurrentByLocation(Float longitude, Float latitude, Integer userId, String language, String units) {
    String cityFound;
    String responseToUser;
    try {
        String completURL = BASEURL + CURRENTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon="
                + URLEncoder.encode(longitude + "", "UTF-8") +
                CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);
        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getString("name") + " (" +
                    jsonObject.getJSONObject("sys").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getInt("id"));
            responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
                    cityFound, convertCurrentWeatherToString(jsonObject, language, units, null));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example #17
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city
 *
 * @param city City to get the weather
 * @return userHash to be send to use
 * @note Forecast for the following 3 days
 */
public String fetchWeatherCurrent(String city, Integer userId, String language, String units) {
    String cityFound;
    String responseToUser;
    Emoji emoji = null;
    try {
        String completURL = BASEURL + CURRENTPATH + "?" + getCityQuery(city) +
                CURRENTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);
        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getString("name") + " (" +
                    jsonObject.getJSONObject("sys").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getInt("id"));
            emoji = getEmojiForWeather(jsonObject.getJSONArray("weather").getJSONObject(0));
            responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
                    cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example #18
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city
 *
 * @param city City to get the weather
 * @return userHash to be send to use
 * @note Forecast for the following 3 days
 */
public String fetchWeatherForecast(String city, Integer userId, String language, String units) {
    String cityFound;
    String responseToUser;
    try {
        String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(city) +
                FORECASTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        BotLogger.info(LOGTAG, jsonObject.toString());
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
                    jsonObject.getJSONObject("city").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
            responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
                    cityFound, convertListOfForecastToString(jsonObject, language, units, true));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example #19
Source File: SignatureExec.java    From wechatpay-apache-httpclient with Apache License 2.0 5 votes vote down vote up
protected void convertToRepeatableRequestEntity(HttpRequestWrapper request) throws IOException {
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
    if (entity != null) {
      ((HttpEntityEnclosingRequest) request).setEntity(new BufferedHttpEntity(entity));
    }
  }
}
 
Example #20
Source File: HttpClientRequestor.java    From http-api-invoker with MIT License 5 votes vote down vote up
private HttpResponse sendRequest(HttpRequest request, HttpRequestBase httpRequestBase) throws IOException {
    prepare(request, httpRequestBase);
    CloseableHttpResponse response = httpClient.execute(httpRequestBase);
    if (response.getEntity() != null) {
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        EntityUtils.consume(response.getEntity());
    }
    return new HttpClientResponse(response);
}
 
Example #21
Source File: HttpClientRequestor.java    From http-api-invoker with MIT License 5 votes vote down vote up
private HttpResponse sendMultiPartRequest(HttpRequest request, HttpRequestBase httpRequestBase) throws IOException {
    prepare(request, httpRequestBase);
    CloseableHttpClient httpClient = null;
    try {
        httpClient = createHttpClient();
        CloseableHttpResponse response = httpClient.execute(httpRequestBase);
        response.setEntity(new BufferedHttpEntity(response.getEntity()));
        EntityUtils.consume(response.getEntity());
        return new HttpClientResponse(response);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
 
Example #22
Source File: AsyncHttpResponseHandler.java    From letv with Apache License 2.0 5 votes vote down vote up
protected void sendResponseMessage(HttpResponse response) {
    Throwable e;
    StatusLine status = response.getStatusLine();
    String responseBody = null;
    try {
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            HttpEntity entity = new BufferedHttpEntity(temp);
            try {
                responseBody = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException e2) {
                e = e2;
                HttpEntity httpEntity = entity;
                sendFailureMessage(e, null);
                if (status.getStatusCode() >= 300) {
                    sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
                } else {
                    sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
                }
            }
        }
    } catch (IOException e3) {
        e = e3;
        sendFailureMessage(e, null);
        if (status.getStatusCode() >= 300) {
            sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
        } else {
            sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
        }
    }
    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}
 
Example #23
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Utility function for creating a new BufferedEntity and wrapping any errors
 * as a SdkClientException.
 *
 * @param entity The HTTP entity to wrap with a buffered HTTP entity.
 * @return A new BufferedHttpEntity wrapping the specified entity.
 */
public static HttpEntity newBufferedHttpEntity(HttpEntity entity) {
    try {
        return new BufferedHttpEntity(entity);
    } catch (IOException e) {
        throw new UncheckedIOException("Unable to create HTTP entity: " + e.getMessage(), e);
    }
}
 
Example #24
Source File: TelegramBot.java    From telegram-notifications-plugin with MIT License 5 votes vote down vote up
private String sendHttpPostRequest(HttpPost httpPost) throws IOException {
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        HttpEntity httpEntity = response.getEntity();
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
        return EntityUtils.toString(bufferedHttpEntity, StandardCharsets.UTF_8);
    }
}
 
Example #25
Source File: HttpClientImageDownloader.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
	HttpGet httpRequest = new HttpGet(imageUri);
	HttpResponse response = httpClient.execute(httpRequest);
	HttpEntity entity = response.getEntity();
	BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
	return bufHttpEntity.getContent();
}
 
Example #26
Source File: FusionKrb5HttpClientConfigurer.java    From storm-solr with Apache License 2.0 5 votes vote down vote up
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
  if (request instanceof HttpEntityEnclosingRequest) {
    HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
    HttpEntity requestEntity = enclosingRequest.getEntity();
    enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
  }
}
 
Example #27
Source File: DirectionsService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the directions
 *
 * @param origin Origin address
 * @param destination Destination address
 * @return Destinations
 */
public List<String> getDirections(String origin, String destination, String language) {
    final List<String> responseToUser = new ArrayList<>();
    try {
        String completURL = BASEURL + "?origin=" + getQuery(origin) + "&destination=" +
                getQuery(destination) + PARAMS.replace("@language@", language) + APIIDEND;
        HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);
        HttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseContent = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseContent);
        if (jsonObject.getString("status").equals("OK")) {
            JSONObject route = jsonObject.getJSONArray("routes").getJSONObject(0);
            String startOfAddress = LocalisationService.getString("directionsInit", language);
            String partialResponseToUser = String.format(startOfAddress,
                    route.getJSONArray("legs").getJSONObject(0).getString("start_address"),
                    route.getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text"),
                    route.getJSONArray("legs").getJSONObject(0).getString("end_address"),
                    route.getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text")
                    );
            responseToUser.add(partialResponseToUser);
            responseToUser.addAll(getDirectionsSteps(
                    route.getJSONArray("legs").getJSONObject(0).getJSONArray("steps"), language));
        } else {
            responseToUser.add(LocalisationService.getString("directionsNotFound", language));
        }
    } catch (Exception e) {
        BotLogger.warn(LOGTAG, e);
        responseToUser.add(LocalisationService.getString("errorFetchingDirections", language));
    }
    return responseToUser;
}
 
Example #28
Source File: WeatherService.java    From TelegramBotsExample with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch the weather of a city for one day
 *
 * @param cityId City to get the weather
 * @return userHash to be send to use
 * @note Forecast for the day
 */
public String fetchWeatherAlert(int cityId, int userId, String language, String units) {
    String cityFound;
    String responseToUser;
    try {
        String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(cityId + "") +
                ALERTPARAMS.replace("@language@", language).replace("@units@", units) + APIIDEND;
        CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpGet request = new HttpGet(completURL);

        CloseableHttpResponse response = client.execute(request);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);
        String responseString = EntityUtils.toString(buf, "UTF-8");

        JSONObject jsonObject = new JSONObject(responseString);
        BotLogger.info(LOGTAG, jsonObject.toString());
        if (jsonObject.getInt("cod") == 200) {
            cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
                    jsonObject.getJSONObject("city").getString("country") + ")";
            saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
            responseToUser = String.format(LocalisationService.getString("weatherAlert", language),
                    cityFound, convertListOfForecastToString(jsonObject, language, units, false));
        } else {
            BotLogger.warn(LOGTAG, jsonObject.toString());
            responseToUser = LocalisationService.getString("cityNotFound", language);
        }
    } catch (Exception e) {
        BotLogger.error(LOGTAG, e);
        responseToUser = LocalisationService.getString("errorFetchingWeather", language);
    }
    return responseToUser;
}
 
Example #29
Source File: SignatureExec.java    From wechatpay-apache-httpclient with Apache License 2.0 5 votes vote down vote up
protected void convertToRepeatableResponseEntity(CloseableHttpResponse response)
    throws IOException {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    response.setEntity(new BufferedHttpEntity(entity));
  }
}
 
Example #30
Source File: BufferedHttpEntityFactory.java    From BUbiNG with Apache License 2.0 4 votes vote down vote up
@Override
public HttpEntity newEntity(final HttpEntity from) throws IOException {
	return new BufferedHttpEntity(from);
}