HttpEntity實(shí)體即可以使流也可以使字符串形式。
具體有什么用法看他的方法解釋:
[html] view plain copypackage 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("這一個(gè)字符串實(shí)體", "UTF-8"); //內(nèi)容類型 System.out.PRintln(entity.getContentType()); //內(nèi)容的編碼格式 System.out.println(entity.getContentEncoding()); //內(nèi)容的長(zhǎng)度 System.out.println(entity.getContentLength()); //把內(nèi)容轉(zhuǎn)成字符串 System.out.println(EntityUtils.toString(entity)); //內(nèi)容轉(zhuǎn)成字節(jié)數(shù)組 System.out.println(EntityUtils.toByteArray(entity).length); //還有個(gè)直接獲得流 //entity.getContent(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (ParseException e) { } catch (IOException e) { } } } 對(duì)于實(shí)體的資源使用完之后要適當(dāng)?shù)幕厥召Y源,特別是對(duì)于流實(shí)體:例子代碼如下[html] view plain copypublic static void test() throws IllegalStateException, IOException{ HttpResponse response = null; HttpEntity entity = response.getEntity(); if(entity!=null){ InputStream is = entity.getContent(); try{ //做一些操作 }finally{ //最后別忘了關(guān)閉應(yīng)該關(guān)閉的資源,適當(dāng)?shù)尼尫刨Y源 if(is != null){ is.close(); } //這個(gè)方法也可以把底層的流給關(guān)閉了 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(); } } }*/ } }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注