本文整理汇总了Java中ch.boye.httpclientandroidlib.HttpEntity类的典型用法代码示例。如果您正苦于以下问题:Java HttpEntity类的具体用法?Java HttpEntity怎么用?Java HttpEntity使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpEntity类属于ch.boye.httpclientandroidlib包,在下文中一共展示了HttpEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: process
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
if (request instanceof HttpEntityEnclosingRequest) {
final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
// Do not send the expect header if request body is known to be empty
if (entity != null
&& entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
final boolean active = request.getParams().getBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, this.activeByDefault);
if (active) {
request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
}
}
}
}
}
示例2: process
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
Args.notNull(request, "HTTP request");
if (!request.containsHeader(HTTP.EXPECT_DIRECTIVE)) {
if (request instanceof HttpEntityEnclosingRequest) {
final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
// Do not send the expect header if request body is known to be empty
if (entity != null
&& entity.getContentLength() != 0 && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig config = clientContext.getRequestConfig();
if (config.isExpectContinueEnabled()) {
request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
}
}
}
}
}
示例3: parse
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Returns a list of {@link NameValuePair NameValuePairs} as parsed from an {@link HttpEntity}. The encoding is
* taken from the entity's Content-Encoding header.
* <p>
* This is typically used while parsing an HTTP POST.
*
* @param entity
* The entity to parse
* @return a list of {@link NameValuePair} as built from the URI's query portion.
* @throws IOException
* If there was an exception getting the entity's data.
*/
public static List <NameValuePair> parse(
final HttpEntity entity) throws IOException {
final ContentType contentType = ContentType.get(entity);
if (contentType != null && contentType.getMimeType().equalsIgnoreCase(CONTENT_TYPE)) {
final String content = EntityUtils.toString(entity, Consts.ASCII);
if (content != null && content.length() > 0) {
Charset charset = contentType.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
return parse(content, charset, QP_SEPS);
}
}
return Collections.emptyList();
}
示例4: toByteArray
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Read the contents of an entity and return it as a byte array.
*
* @param entity the entity to read from=
* @return byte array containing the entity content. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws IOException if an error occurs reading the input stream
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
*/
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
Args.notNull(entity, "Entity");
final InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
"HTTP entity too large to be buffered in memory");
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
final byte[] tmp = new byte[4096];
int l;
while((l = instream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
instream.close();
}
}
示例5: getContentCharSet
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*
* @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
*/
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
Args.notNull(entity, "Entity");
String charset = null;
if (entity.getContentType() != null) {
final HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
final NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
示例6: generateResponse
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* If I was able to use a {@link CacheEntity} to response to the {@link ch.boye.httpclientandroidlib.HttpRequest} then
* generate an {@link HttpResponse} based on the cache entry.
* @param entry
* {@link CacheEntity} to transform into an {@link HttpResponse}
* @return {@link HttpResponse} that was constructed
*/
CloseableHttpResponse generateResponse(final HttpCacheEntry entry) {
final Date now = new Date();
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, entry
.getStatusCode(), entry.getReasonPhrase());
response.setHeaders(entry.getAllHeaders());
if (entry.getResource() != null) {
final HttpEntity entity = new CacheEntity(entry);
addMissingContentLengthHeader(response, entity);
response.setEntity(entity);
}
final long age = this.validityStrategy.getCurrentAgeSecs(entry, now);
if (age > 0) {
if (age >= Integer.MAX_VALUE) {
response.setHeader(HeaderConstants.AGE, "2147483648");
} else {
response.setHeader(HeaderConstants.AGE, "" + ((int) age));
}
}
return Proxies.enhanceResponse(response);
}
示例7: doConsume
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
private void doConsume() throws IOException {
ensureNotConsumed();
consumed = true;
limit = new InputLimit(maxResponseSizeBytes);
final HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
final String uri = request.getRequestLine().getUri();
instream = entity.getContent();
try {
resource = resourceFactory.generate(uri, instream, limit);
} finally {
if (!limit.isReached()) {
instream.close();
}
}
}
示例8: getReconstructedResponse
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
CloseableHttpResponse getReconstructedResponse() throws IOException {
ensureConsumed();
final HttpResponse reconstructed = new BasicHttpResponse(response.getStatusLine());
reconstructed.setHeaders(response.getAllHeaders());
final CombinedEntity combinedEntity = new CombinedEntity(resource, instream);
final HttpEntity entity = response.getEntity();
if (entity != null) {
combinedEntity.setContentType(entity.getContentType());
combinedEntity.setContentEncoding(entity.getContentEncoding());
combinedEntity.setChunked(entity.isChunked());
}
reconstructed.setEntity(combinedEntity);
return (CloseableHttpResponse) Proxy.newProxyInstance(
ResponseProxyHandler.class.getClassLoader(),
new Class<?>[] { CloseableHttpResponse.class },
new ResponseProxyHandler(reconstructed) {
@Override
public void close() throws IOException {
response.close();
}
});
}
示例9: jsonObjectBody
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Return the body as a <b>non-null</b> <code>ExtendedJSONObject</code>.
*
* @return A non-null <code>ExtendedJSONObject</code>.
*
* @throws IllegalStateException
* @throws IOException
* @throws NonObjectJSONException
*/
public ExtendedJSONObject jsonObjectBody() throws IllegalStateException, IOException, NonObjectJSONException {
if (body != null) {
// Do it from the cached String.
return new ExtendedJSONObject(body);
}
HttpEntity entity = this.response.getEntity();
if (entity == null) {
throw new IOException("no entity");
}
InputStream content = entity.getContent();
try {
Reader in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
return new ExtendedJSONObject(in);
} finally {
content.close();
}
}
示例10: jsonArrayBody
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
public JSONArray jsonArrayBody() throws NonArrayJSONException, IOException {
final JSONParser parser = new JSONParser();
try {
if (body != null) {
// Do it from the cached String.
return (JSONArray) parser.parse(body);
}
final HttpEntity entity = this.response.getEntity();
if (entity == null) {
throw new IOException("no entity");
}
final InputStream content = entity.getContent();
final Reader in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
try {
return (JSONArray) parser.parse(in);
} finally {
in.close();
}
} catch (ClassCastException | ParseException e) {
NonArrayJSONException exception = new NonArrayJSONException("value must be a json array");
exception.initCause(e);
throw exception;
}
}
示例11: getPayloadHashString
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Get the payload verification hash for the given request, if possible.
* <p>
* Returns null if the request does not enclose an entity (is not an HTTP
* PATCH, POST, or PUT). Throws if the payload verification hash cannot be
* computed.
*
* @param request
* to compute hash for.
* @return verification hash, or null if the request does not enclose an entity.
* @throws IllegalArgumentException if the request does not enclose a valid non-null entity.
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
* @throws IOException
*/
protected static String getPayloadHashString(HttpRequestBase request)
throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException, IllegalArgumentException {
final boolean shouldComputePayloadHash = request instanceof HttpEntityEnclosingRequest;
if (!shouldComputePayloadHash) {
Logger.debug(LOG_TAG, "Not computing payload verification hash for non-enclosing request.");
return null;
}
if (!(request instanceof HttpEntityEnclosingRequest)) {
throw new IllegalArgumentException("Cannot compute payload verification hash for enclosing request without an entity");
}
final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity == null) {
throw new IllegalArgumentException("Cannot compute payload verification hash for enclosing request with a null entity");
}
return Base64.encodeBase64String(getPayloadHash(entity));
}
示例12: getPayloadHash
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Generate the SHA-256 hash of a normalized Hawk payload generated from an
* HTTP entity.
* <p>
* <b>Warning:</b> the entity <b>must</b> be repeatable. If it is not, this
* code throws an <code>IllegalArgumentException</code>.
* <p>
* This is under-specified; the code here was reverse engineered from the code
* at
* <a href="https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L81">https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L81</a>.
* @param entity to normalize and hash.
* @return hash.
* @throws IllegalArgumentException if entity is not repeatable.
*/
protected static byte[] getPayloadHash(HttpEntity entity) throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException {
if (!entity.isRepeatable()) {
throw new IllegalArgumentException("entity must be repeatable");
}
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(("hawk." + HAWK_HEADER_VERSION + ".payload\n").getBytes("UTF-8"));
digest.update(getBaseContentType(entity.getContentType()).getBytes("UTF-8"));
digest.update("\n".getBytes("UTF-8"));
InputStream stream = entity.getContent();
try {
int numRead;
byte[] buffer = new byte[4096];
while (-1 != (numRead = stream.read(buffer))) {
if (numRead > 0) {
digest.update(buffer, 0, numRead);
}
}
digest.update("\n".getBytes("UTF-8")); // Trailing newline is specified by Hawk.
return digest.digest();
} finally {
stream.close();
}
}
示例13: executeRequest
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
private JSONObject executeRequest(HttpUriRequest request) throws TeslaApiException {
try {
final HttpResponse httpResponse = httpClient.execute(request);
Log.d(Config.TAG, "Status: " + httpResponse.getStatusLine());
final int status = httpResponse.getStatusLine().getStatusCode();
if (HttpStatus.isSuccessful(status)) {
final HttpEntity entity = httpResponse.getEntity();
final String responseString = EntityUtils.toString(entity, "UTF-8");
Log.d(Config.TAG, "Response: " + responseString);
return new JSONObject(responseString);
} else {
throw TeslaApiException.fromCode(status);
}
} catch (IOException | JSONException e) {
throw new TeslaApiException(e);
}
}
示例14: decodeEntity
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
public Object decodeEntity(HttpEntity httpentity) throws JSONException {
JSONObject jsonobject = null;
String jsonString;
if (httpentity == null) {
return null;
}
try {
jsonString = EntityUtils.toString(httpentity).trim();
} catch (Exception e) {
Log.e("JsonObjectEntityDecoder", "decodeEntity", e);
return null;
}
if (!jsonString.isEmpty()) {
jsonobject = new JSONObject(jsonString);
}
return jsonobject;
}
示例15: downloadAndDecodeImage
import ch.boye.httpclientandroidlib.HttpEntity; //导入依赖的package包/类
/**
* Download the Favicon from the given URL and pass it to the decoder function.
*
* @param targetFaviconURL URL of the favicon to download.
* @return A LoadFaviconResult containing the bitmap(s) extracted from the downloaded file, or
* null if no or corrupt data ware received.
* @throws IOException If attempts to fully read the stream result in such an exception, such as
* in the event of a transient connection failure.
* @throws URISyntaxException If the underlying call to tryDownload retries and raises such an
* exception trying a fallback URL.
*/
private LoadFaviconResult downloadAndDecodeImage(URI targetFaviconURL) throws IOException, URISyntaxException {
// Try the URL we were given.
HttpResponse response = tryDownload(targetFaviconURL);
if (response == null) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
// Decode the image from the fetched response.
try {
return decodeImageFromResponse(entity);
} finally {
// Close the stream and free related resources.
entity.consumeContent();
}
}