List of usage examples for org.apache.http.entity BufferedHttpEntity BufferedHttpEntity
public BufferedHttpEntity(HttpEntity httpEntity) throws IOException
From source file:org.apache.abdera2.protocol.client.AbderaResponseHandler.java
private static InputStream getInputStream(HttpResponse response) throws IOException { InputStream in = null;//from ww w.j a va 2 s .c o m Header he = response.getFirstHeader("Content-Encoding"); String ce = he != null ? he.getValue() : null; BufferedHttpEntity buffer = new BufferedHttpEntity(response.getEntity()); in = buffer.getContent(); if (ce != null && in != null) in = Compression.wrap(in, ce); return in; }
From source file:com.frand.easyandroid.http.FFStringRespHandler.java
/** * ?????/*from w w w. j a v a 2 s .c om*/ * ??SUCCESS_MESSAGEkey??handler? * ??FAILURE_MESSAGEkey??handler? * @param response * @param reqTag * @param reqUrl */ protected void sendRespMsg(HttpResponse response, int reqTag, String reqUrl) { StatusLine status = response.getStatusLine(); String responseBody = null; try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, "UTF-8"); } } catch (IOException e) { sendFailureMsg(e, reqTag, reqUrl); } if (status.getStatusCode() >= 300) { sendFailureMsg(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), reqTag, reqUrl); } else { sendSuccMsg(responseBody, reqTag, reqUrl); } }
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 w w w .j av a 2 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:ca.marcmeszaros.papyrus.remote.DownloadThumbnails.java
@Override protected LinkedList<Bitmap> doInBackground(URL... urls) { // some class variables HttpGet httpRequest;//w w w. ja v a 2 s . co m Bitmap bm; LinkedList<Bitmap> bitmaps = new LinkedList<Bitmap>(); try { // loop through all urls for (URL url : urls) { // create the HTTP request httpRequest = new HttpGet(url.toURI()); // create an HTTP client and get the response HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); // get a handle on the http entity HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); // read the entity from the stream into a bitmap object bm = BitmapFactory.decodeStream(instream); // add the bitmap to the list bitmaps.add(bm); } } catch (URISyntaxException e) { Log.e(TAG, "URISyntaxException", e); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException", e); } catch (IOException e) { Log.e(TAG, "IOException", e); } return bitmaps; }
From source file:cn.com.lowe.android.tools.net.response.HtmlHttpResponseHandler.java
@Override public void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); String responseBody = null;/* w w w . j a va2 s.c om*/ try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, ENCODING); } } catch (IOException e) { sendFailureMessage(e, (String) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } }
From source file:org.digidoc4j.impl.bdoc.SKOcspDataLoader.java
@Override public byte[] post(final String url, final byte[] content) throws DSSException { logger.info("Getting OCSP response from " + url); HttpPost httpRequest = null;/* w w w. j av a2 s . c o m*/ HttpResponse httpResponse = null; try { final URI uri = URI.create(url.trim()); httpRequest = new HttpPost(uri); httpRequest.setHeader("User-Agent", userAgent); // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this information. // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards. // This is because, it may not be possible to reset the stream (= go to position 0). // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a byte-array. final ByteArrayInputStream bis = new ByteArrayInputStream(content); final HttpEntity httpEntity = new InputStreamEntity(bis, content.length); final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); httpRequest.setEntity(requestEntity); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } httpResponse = getHttpResponse(httpRequest, url); final byte[] returnedBytes = readHttpResponse(url, httpResponse); return returnedBytes; } catch (IOException e) { throw new DSSException(e); } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:ch.cyberduck.core.b2.B2ErrorResponseInterceptor.java
@Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_UNAUTHORIZED: if (executionCount <= MAX_RETRIES) { final B2ApiException failure; try { EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); failure = new B2ApiException(EntityUtils.toString(response.getEntity()), new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); if (new B2ExceptionMappingService().map(failure) instanceof ExpiredTokenException) { // The authorization token is valid for at most 24 hours. try { authorizationToken = session.getClient().authenticate(accountId, applicationKey) .getAuthorizationToken(); return true; } catch (B2ApiException | IOException e) { log.warn(String.format("Attempt to renew expired auth token failed. %s", e.getMessage())); return false; }/*from w w w .j a va 2 s . c o m*/ } } catch (IOException e) { log.warn(String.format("Failure parsing response entity from %s", response)); return false; } } } return false; }
From source file:ch.cyberduck.core.sds.SDSErrorResponseInterceptor.java
@Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_UNAUTHORIZED: if (executionCount <= MAX_RETRIES) { final ApiException failure; try { EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); failure = new ApiException(response.getStatusLine().getStatusCode(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())); if (new SDSExceptionMappingService().map(failure) instanceof ExpiredTokenException) { // The provided token is valid for two hours, every usage resets this period to two full hours again. Logging off invalidates the token. try { token = new AuthApi(session.getClient()).login( new LoginRequest().authType(session.getHost().getProtocol().getAuthorization()) .login(user).password(password)) .getToken(); return true; } catch (ApiException e) { // {"code":401,"message":"Unauthorized","debugInfo":"Wrong username or password","errorCode":-10011} log.warn(String.format("Attempt to renew expired auth token failed. %s", e.getMessage())); return false; }//from ww w. j a va2 s . c o m } } catch (IOException e) { log.warn(String.format("Failure parsing response entity from %s", response)); return false; } } } return false; }
From source file:com.nimpres.android.web.APIContact.java
/** * Performs a post request to the specified api with the specified parameters and returns the result * // w w w .j a v a 2 s .co m * @param apiAddress * @param postParams * @return the result in an HttpEntity object */ public static BufferedHttpEntity apiPostRequest(String apiAddress, List<NameValuePair> postParams) { BufferedHttpEntity resEntity = null; try { HttpClient client = new DefaultHttpClient(); // Set address for API call HttpPost post = new HttpPost(getAPIAddress(apiAddress)); // Add post parameters to request UrlEncodedFormEntity ent = new UrlEncodedFormEntity(postParams, HTTP.UTF_8); post.setEntity(ent); // Send post and store result Log.d("APIContact", "Contacting API - api-method:" + apiAddress + ", api-query: " + postParams); HttpResponse responsePOST = client.execute(post); resEntity = new BufferedHttpEntity(responsePOST.getEntity()); String result = EntityUtils.toString(resEntity); Log.d("APIContact", "post result: " + result); if (resEntity != null) { return resEntity; } } catch (Exception e) { e.printStackTrace(); } return null; }