最近在學習安卓並用thinkphp做后台,為了抵抗自己的爛記性,就在這里記錄一下當我從tp后台獲取到json串傳到安卓客戶端所用到的一個方法函數。
EntityUtils對象是org.apache.http.util下的一個工具類,用官方的解釋是為HttpEntity對象提供的靜態幫助類,其常用的幾個方法如下:
consume()方法;
consumeQuietly(HttpEntity)方法
toByteArray(final HttpEntity entity)方法
最主要的就是consume()這個方法,其功能就是關閉HttpEntity是的流,如果手動關閉了InputStream instream = entity.getContent();這個流,也可以不調用這個方法。看看了其源碼就知道了:
而我在項目中用到的是
String data = EntityUtils.toString(response.getEntity());
我會在下一篇文章中把tp和安卓客戶端的數據交互代碼粘出來
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 {
HttpEntityentity=newStringEntity("這一個字符串實體", "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) {
}
}
}
對於實體的資源使用完之后要適當的回收資源,特別是對於流實體:例子代碼如下
public static void test() throws IllegalStateException, IOException{
HttpResponseresponse=null;
HttpEntityentity=response.getEntity();
if(entity!=null){
InputStreamis=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()) {
InputStreaminstream=entity.getContent();
if (instream != null) {
instream.close();
}
}
}*/
}
}
