Java Code Examples for org.apache.http.HttpEntity#consumeContent()

The following examples show how to use org.apache.http.HttpEntity#consumeContent() . These examples are extracted from open source projects. 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 Project: Mobike   File: AsyncHttpClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which
 * doesn't chain call consumeContent on underlying wrapped HttpEntity
 *
 * @param entity HttpEntity, may be null
 */
public static void endEntityViaReflection(HttpEntity entity) {
    if (entity instanceof HttpEntityWrapper) {
        try {
            Field f = null;
            Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
            for (Field ff : fields) {
                if (ff.getName().equals("wrappedEntity")) {
                    f = ff;
                    break;
                }
            }
            if (f != null) {
                f.setAccessible(true);
                HttpEntity wrapped = (HttpEntity) f.get(entity);
                if (wrapped != null) {
                    wrapped.consumeContent();
                }
            }
        } catch (Throwable t) {
            Log.e(LOG_TAG, "wrappedEntity consume", t);
        }
    }
}
 
Example 2
/**
 * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which
 * doesn't chain call consumeContent on underlying wrapped HttpEntity
 *
 * @param entity HttpEntity, may be null
 */
public static void endEntityViaReflection(HttpEntity entity) {
    if (entity instanceof HttpEntityWrapper) {
        try {
            Field f = null;
            Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
            for (Field ff : fields) {
                if (ff.getName().equals("wrappedEntity")) {
                    f = ff;
                    break;
                }
            }
            if (f != null) {
                f.setAccessible(true);
                HttpEntity wrapped = (HttpEntity) f.get(entity);
                if (wrapped != null) {
                    wrapped.consumeContent();
                }
            }
        } catch (Throwable t) {
            Log.e(LOG_TAG, "wrappedEntity consume", t);
        }
    }
}
 
Example 3
/**
 * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which
 * doesn't chain call consumeContent on underlying wrapped HttpEntity
 *
 * @param entity HttpEntity, may be null
 */
public static void endEntityViaReflection(HttpEntity entity) {
    if (entity instanceof HttpEntityWrapper) {
        try {
            Field f = null;
            Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
            for (Field ff : fields) {
                if (ff.getName().equals("wrappedEntity")) {
                    f = ff;
                    break;
                }
            }
            if (f != null) {
                f.setAccessible(true);
                HttpEntity wrapped = (HttpEntity) f.get(entity);
                if (wrapped != null) {
                    wrapped.consumeContent();
                }
            }
        } catch (Throwable t) {
            Log.e(LOG_TAG, "wrappedEntity consume", t);
        }
    }
}
 
Example 4
/**
 * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which
 * doesn't chain call consumeContent on underlying wrapped HttpEntity
 *
 * @param entity HttpEntity, may be null
 */
public static void endEntityViaReflection(HttpEntity entity) {
    if (entity instanceof HttpEntityWrapper) {
        try {
            Field f = null;
            Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
            for (Field ff : fields) {
                if (ff.getName().equals("wrappedEntity")) {
                    f = ff;
                    break;
                }
            }
            if (f != null) {
                f.setAccessible(true);
                HttpEntity wrapped = (HttpEntity) f.get(entity);
                if (wrapped != null) {
                    wrapped.consumeContent();
                }
            }
        } catch (Throwable t) {
            Log.e(LOG_TAG, "wrappedEntity consume", t);
        }
    }
}
 
Example 5
Source Project: pearl   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 6
Source Project: AndroidProjects   File: BasicNetwork.java    License: MIT License 5 votes vote down vote up
/**
 * Reads the contents of HttpEntity into a byte[].
 */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 7
Source Project: DaVinci   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity, Request request) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int progress = 0;
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
            progress += count;
            request.progressUpdate(progress);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VinciLog.d("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 8
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 9
Source Project: SimplifyReader   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 10
Source Project: volley_demo   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 11
Source Project: FeedListViewDemo   File: BasicNetwork.java    License: MIT License 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 12
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 13
Source Project: android-discourse   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the contents of HttpEntity into a byte[].
 */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 14
Source Project: product-emm   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        int count;
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 15
Source Project: jivejdon   File: HttpClientUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static String getContent(HttpResponse res, String encoding) throws Exception {
	HttpEntity ent = res.getEntity();
	String result = IOUtils.toString(ent.getContent(), encoding);
	ent.consumeContent();
	return result;
}
 
Example 16
Source Project: volley   File: BasicNetwork.java    License: Apache License 2.0 4 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(ResponseDelivery delivery, Request<?> request, HttpEntity entity) throws IOException, ServerError {
    PoolingByteArrayOutputStream bytes =
            new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
    byte[] buffer = null;
    long time = SystemClock.uptimeMillis();
    try {
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        buffer = mPool.getBuf(1024);
        long length = entity.getContentLength();
        long current = 0;
        int count = -1;
        LoadingListener listener = request.getLoadingListener();
        while ((count = in.read(buffer)) != -1) {
            bytes.write(buffer, 0, count);
            current += count;
            if (listener != null) {
                long thisTime = SystemClock.uptimeMillis();
                if(thisTime - time >= request.getRate()) {
                    time = thisTime;
                    delivery.postLoading(request, length == -1 ? current * 2 : length, current);
                }
            }
        }
        if (listener != null) {
            delivery.postLoading(request, length == -1 ? current : length, current);
        }
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        mPool.returnBuf(buffer);
        bytes.close();
    }
}
 
Example 17
Source Project: EverMemo   File: TEvernoteHttpClient.java    License: MIT License 4 votes vote down vote up
public void flush() throws TTransportException {
  long timer = System.currentTimeMillis();

  HttpEntity httpEntity = null;

  // Extract request and reset buffer
  try {
    // Prepare http post request
    HttpPost request = new HttpPost(url_.toExternalForm());
    this.request = request;
    request.addHeader("Content-Type", "application/x-thrift");
    request.addHeader("Cache-Control", "no-transform");
    if (customHeaders_ != null) {
      for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
        request.addHeader(header.getKey(), header.getValue());
      }
    }
    InputStreamEntity entity =
        new InputStreamEntity(requestBuffer_.getInputStream(), requestBuffer_
            .getSize());
    request.setEntity(entity);
    request.addHeader("Accept", "application/x-thrift");
    request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient"
        : userAgent);
    request.getParams().setBooleanParameter(
        CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    DefaultHttpClient dHTTP = getHTTPClient();
    HttpResponse response = dHTTP.execute(request);
    httpEntity = response.getEntity();

    int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode != 200) {
      if (httpEntity != null) {
        httpEntity.consumeContent();
      }
      throw new TTransportException("HTTP Response code: " + responseCode);
    }
    // Read the responses
    requestBuffer_.reset();
    inputStream_ = response.getEntity().getContent();
  } catch (IOException iox) {
    throw new TTransportException(iox);
  } catch (Exception ex) {
    throw new TTransportException(ex);
  } finally {
    try {
      requestBuffer_.reset();
    } catch (IOException e) {
    }
    this.request = null;
  }
}
 
Example 18
public Bitmap Task(String url) {
	final DefaultHttpClient client = new DefaultHttpClient();

	// forming a HttoGet request
	final HttpGet getRequest = new HttpGet(url);
	try {

		HttpResponse response = client.execute(getRequest);

		// check 200 OK for success
		final int statusCode = response.getStatusLine().getStatusCode();

		if (statusCode != HttpStatus.SC_OK) {
			Log.w("ImageDownloader", "Error " + statusCode
					+ " while retrieving bitmap from " + url);
			return null;

		}

		final HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream inputStream = null;
			try {
				// getting contents from the stream
				inputStream = entity.getContent();

				// decoding stream data back into image Bitmap that
				// android understands
				final Bitmap bitmap = BitmapFactory
						.decodeStream(inputStream);

				return bitmap;
			} finally {
				if (inputStream != null) {
					inputStream.close();
				}
				entity.consumeContent();
			}
		}
	} catch (Exception e) {
		// You Could provide a more explicit error message for
		// IOException
		getRequest.abort();
		handlernum = -1;
		Log.e("ImageDownloader", "Something went wrong while"
				+ " retrieving bitmap from " + url + e.toString());
	}
	return null;
}
 
Example 19
Source Project: SaveVolley   File: BasicNetwork.java    License: Apache License 2.0 4 votes vote down vote up
/** Reads the contents of HttpEntity into a byte[]. */
/*
 * 执行 Apache HttpEntity -> byte[] 的转化
 */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
    /*
     * 实例化一个 PoolingByteArrayOutputStream 对象
     *
     * PoolingByteArrayOutputStream 内设置了一个 ByteArrayPool,会将一些 实例化好的 byte[] 进行缓存
     * 然后回收利用,提供读取流数据
     *
     * 将当前 BasicNetwork 的 ByteArrayPool 提供 给 PoolingByteArrayOutputStream
     * 还需要将 传入一个 需要 output 的数据长度 给 PoolingByteArrayOutputStream,这里用
     * (int) entity.getContentLength() 进行获取
     */
    PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool,
            (int) entity.getContentLength());
    byte[] buffer = null;
    try {
        // 获取 Apache HttpEntity 的 content 数据流
        InputStream in = entity.getContent();
        if (in == null) {
            throw new ServerError();
        }
        // 获取一个 byte[].length = 1024 的 byte[]
        buffer = mPool.getBuf(1024);
        int count;
        // 开始 边读边写
        while ((count = in.read(buffer)) != -1) {
            // 写入到 PoolingByteArrayOutputStream 中
            bytes.write(buffer, 0, count);
        }
        // 从 PoolingByteArrayOutputStream 中取出 byte[] 数据
        return bytes.toByteArray();
    } finally {
        try {
            // Close the InputStream and release the resources by "consuming the content".
            // 调用 Apache API 关闭 Apache HttpEntity 的 content 数据流
            entity.consumeContent();
        } catch (IOException e) {
            // This can happen if there was an exception above that left the entity in
            // an invalid state.
            VolleyLog.v("Error occured when calling consumingContent");
        }
        // 将使用的 byte[] 放入 ByteArrayPool 缓存回收
        mPool.returnBuf(buffer);
        // 关闭 PoolingByteArrayOutputStream 流
        bytes.close();
    }
}
 
Example 20
private Bitmap downloadBitmapWithClient(String url) {
    final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
    HttpClientParams.setRedirecting(httpClient.getParams(), true);
    final HttpGet request = new HttpGet(url);

    try {
        HttpResponse response = httpClient.execute(request);
        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Location");

            if (headers != null && headers.length != 0) {
                String newUrl = headers[headers.length - 1].getValue();
                // call again with new URL
                return downloadBitmap(newUrl);
            } else {
                return null;
            }
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();

                // do your work here
                return BitmapFactory.decodeStream(inputStream);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        request.abort();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }

    return null;
}