1 BasicHttpEntity
代表底層流的基本實體。通常是在http報文中獲取的實體。他只有一個空參的構造方法。剛創建時沒有內容,長度爲負值。需要通過兩個方法,把值賦進去。
- /**
- * BasicHttpEntity
- * @throws IOException
- */
- public static void testBasicHttpEntity() throws IOException{
- InputStream is = null;
- //BasicHttpEntity這類就是一個輸入流的內容包裝類,包裝內容的相關的編碼格式,長度等
- BasicHttpEntity entity = new BasicHttpEntity();
- //設置內容
- entity.setContent(is);
- //設置長度
- entity.setContentLength(is.available());
- //沒搞懂chunked這個屬性啥意思
- entity.setChunked(false);
- }
2 ByteArrayEntity
是自我包含的,可重複獲得使用的,從指定的字節數組中取出內容的實體。字節數組是這個實體的構造方法的參數。
- /**
- * ByteArrayEntity
- * @throws IOException
- */
- public static void testByteArrayEntity() throws IOException{
- ByteArrayEntity entity = new ByteArrayEntity("內容".getBytes());
- ByteArrayInputStream is = (ByteArrayInputStream) entity.getContent();
- //上面這行代碼返回的其實是一個ByteArrayInputStream對象
- /*public InputStream getContent() {
- return new ByteArrayInputStream(this.b, this.off, this.len);
- }*/
- }
3 StringEntity
是自我包含的可重複的實體。通過String創建的實體。有兩個構造方法,一個是自Sring爲參數的構造方法,一個是以String和字符編碼爲參數的構造方法。
- /**
- * StringEntity
- * @throws IOException
- */
- public static void testStringEntity() throws IOException{
- StringBuilder sb = new StringBuilder();
- //獲取系統的信息集合,這個集合是不可以修改的
- Map<String, String> nev = System.getenv();
- for(Entry<String, String> entry : nev.entrySet()){
- sb.append(entry.getKey()).append("=")
- .append(entry.getValue()).append("\n");
- }
- String content = sb.toString();
- System.out.println(content);
- //創建只帶字符串參數的
- StringEntity entity = new StringEntity(content);
- //創建帶字符創參數和字符編碼的
- StringEntity entity2 = new StringEntity(content, "UTF-8");
- }
4 InputreamEntity
是流式不可以重複的實體。構造方法是InputStream 和內容長度,內容長度是輸入流的長度。
- /**
- * InputStreamEntity
- * @throws IOException
- */
- public static void testInputStreamEntity() throws IOException{
- InputStream is = null;
- //InputStreamEntity嚴格是對內容和長度相匹配的。用法和BasicHttpEntity類似
- InputStreamEntity entity = new InputStreamEntity(is, is.available());
- }
5 FileEntity
自我包含式,可以重複的實體。參數傳入文件和文件類型。
- /**
- * FileEntity
- * @throws IOException
- */
- public static void testFileEntity() throws IOException{
- FileEntity entity = new FileEntity(new File(""), ContentType.APPLICATION_FORM_URLENCODED);
- FileEntity entity2 = new FileEntity(new File(""), "application/java-achive");
- }
6 EntityTemplete
從ContentProducer接口接受內容的實體。在ContentProducer的實現類中寫入想要寫入的內容。
- /**
- * EntityTemplate
- * @throws IOException
- */
- public static void testEntityTemplate() throws IOException{
- ContentProducer producer = new ContentProducer() {
- @Override
- public void writeTo(OutputStream outstream) throws IOException {
- outstream.write("這是什麼東東》。".getBytes());
- }
- };
- EntityTemplate entity = new EntityTemplate(producer);
- entity.writeTo(System.out);
- }
7 HttpEntityWrapper
這個是創建被包裝實體的基類,有被包裝實體的引用。相當於實體的代理類,被包裝實體是他的一個屬性。下面是這個類的源碼:
- /*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
- package org.apache.http.entity;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import org.apache.http.Header;
- import org.apache.http.HttpEntity;
- import org.apache.http.annotation.NotThreadSafe;
- /**
- * Base class for wrapping entities.
- * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all
- * calls to it. Implementations of wrapping entities can derive
- * from this class and need to override only those methods that
- * should not be delegated to the wrapped entity.
- *
- * @since 4.0
- */
- @NotThreadSafe
- public class HttpEntityWrapper implements HttpEntity {
- /** The wrapped entity. */
- protected HttpEntity wrappedEntity;
- /**
- * Creates a new entity wrapper.
- *
- * @param wrapped the entity to wrap, not null
- * @throws IllegalArgumentException if wrapped is null
- */
- public HttpEntityWrapper(HttpEntity wrapped) {
- super();
- if (wrapped == null) {
- throw new IllegalArgumentException
- ("wrapped entity must not be null");
- }
- wrappedEntity = wrapped;
- } // constructor
- public boolean isRepeatable() {
- return wrappedEntity.isRepeatable();
- }
- public boolean isChunked() {
- return wrappedEntity.isChunked();
- }
- public long getContentLength() {
- return wrappedEntity.getContentLength();
- }
- public Header getContentType() {
- return wrappedEntity.getContentType();
- }
- public Header getContentEncoding() {
- return wrappedEntity.getContentEncoding();
- }
- public InputStream getContent()
- throws IOException {
- return wrappedEntity.getContent();
- }
- public void writeTo(OutputStream outstream)
- throws IOException {
- wrappedEntity.writeTo(outstream);
- }
- public boolean isStreaming() {
- return wrappedEntity.isStreaming();
- }
- /**
- * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that;
- * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources.
- */
- @Deprecated
- public void consumeContent() throws IOException {
- wrappedEntity.consumeContent();
- }
- }
8 BufferedHttpEntity
是HttpEntityWarpper的子類,可以把不可以重複的實體,實現成可以重複的實體。它從提供的實體中讀取內容,緩存到內容中。源碼如下:
- /*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
- package org.apache.http.entity;
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import org.apache.http.HttpEntity;
- import org.apache.http.annotation.NotThreadSafe;
- import org.apache.http.util.EntityUtils;
- /**
- * A wrapping entity that buffers it content if necessary.
- * The buffered entity is always repeatable.
- * If the wrapped entity is repeatable itself, calls are passed through.
- * If the wrapped entity is not repeatable, the content is read into a
- * buffer once and provided from there as often as required.
- *
- * @since 4.0
- */
- @NotThreadSafe
- public class BufferedHttpEntity extends HttpEntityWrapper {
- private final byte[] buffer;
- /**
- * Creates a new buffered entity wrapper.
- *
- * @param entity the entity to wrap, not null
- * @throws IllegalArgumentException if wrapped is null
- */
- public BufferedHttpEntity(final HttpEntity entity) throws IOException {
- super(entity);
- if (!entity.isRepeatable() || entity.getContentLength() < 0) {
- this.buffer = EntityUtils.toByteArray(entity);
- } else {
- this.buffer = null;
- }
- }
- @Override
- public long getContentLength() {
- if (this.buffer != null) {
- return this.buffer.length;
- } else {
- return wrappedEntity.getContentLength();
- }
- }
- @Override
- public InputStream getContent() throws IOException {
- if (this.buffer != null) {
- return new ByteArrayInputStream(this.buffer);
- } else {
- return wrappedEntity.getContent();
- }
- }
- /**
- * Tells that this entity does not have to be chunked.
- *
- * @return <code>false</code>
- */
- @Override
- public boolean isChunked() {
- return (buffer == null) && wrappedEntity.isChunked();
- }
- /**
- * Tells that this entity is repeatable.
- *
- * @return <code>true</code>
- */
- @Override
- public boolean isRepeatable() {
- return true;
- }
- @Override
- public void writeTo(final OutputStream outstream) throws IOException {
- if (outstream == null) {
- throw new IllegalArgumentException("Output stream may not be null");
- }
- if (this.buffer != null) {
- outstream.write(this.buffer);
- } else {
- wrappedEntity.writeTo(outstream);
- }
- }
- // non-javadoc, see interface HttpEntity
- @Override
- public boolean isStreaming() {
- return (buffer == null) && wrappedEntity.isStreaming();
- }
- } // class BufferedHttpEntity
二 HttpEntity 的使用
1 HttpEntity實體即可以使流也可以使字符串形式。具體有什麼用法看他的方法解釋:
- package com.scl.base;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import org.apache.http.HttpEntity;
- import org.apache.http.ParseException;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.util.EntityUtils;
- public class HttpClientDemo06 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- try {
- HttpEntity entity = new StringEntity("這一個字符串實體", "UTF-8");
- //內容類型
- System.out.println(entity.getContentType());
- //內容的編碼格式
- System.out.println(entity.getContentEncoding());
- //內容的長度
- System.out.println(entity.getContentLength());
- //把內容轉成字符串
- System.out.println(EntityUtils.toString(entity));
- //內容轉成字節數組
- System.out.println(EntityUtils.toByteArray(entity).length);
- //還有個直接獲得流
- //entity.getContent();
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- } catch (ParseException e) {
- } catch (IOException e) {
- }
- }
- }
2 對於實體的資源使用完之後要適當的回收資源,特別是對於流實體。例子代碼如下:
- public static void test() throws IllegalStateException, IOException{
- HttpResponse response = null;
- HttpEntity entity = response.getEntity();
- if(entity!=null){
- InputStream is = entity.getContent();
- try{
- //做一些操作
- }finally{
- //最後別忘了關閉應該關閉的資源,適當的釋放資源
- if(is != null){
- is.close();
- }
- //這個方法也可以把底層的流給關閉了
- EntityUtils.consume(entity);
- //下面是這方法的源碼
- /*public static void consume(final HttpEntity entity) throws IOException {
- if (entity == null) {
- return;
- }
- if (entity.isStreaming()) {
- InputStream instream = entity.getContent();
- if (instream != null) {
- instream.close();
- }
- }
- }*/
- }
- }
- 頂
- 3