标签:
原文: Java InputStream读取网络响应Response数据的方法!(重要)
Java InputStream读取数据问题
======================================================================
原理讲解
1. 关于InputStream.read()
在从数据流里读取数据时,为图简单,经常用InputStream.read()方法。这个方法是从流里每次只读取读取一个字节,效率会非常低。 更好的方法是用InputStream.read(byte[] b)或者InputStream.read(byte[] b,int off,int len)方法,一次读取多个字节。
如果这样写代码:
int count = in.available(); byte[] b = new byte[count]; in.read(b);在进行网络操作时往往出错,因为你调用available()方法时,对发发送的数据可能还没有到达,你得到的count是0。
int count = 0; while (count == 0) { //count = in.available(); count=response.getEntity().getContentLength();//(HttpResponse response) } byte[] b = new byte[count]; in.read(b);
byte[] bytes = new byte[count];
int readCount = 0; // 已经成功读取的字节的个数
while (readCount < count) {
readCount += in.read(bytes, readCount, count - readCount);
}
用这段代码可以保证读取count个字节,除非中途遇到IO异常或者到了数据流的结尾(EOFException).
==========================================================================================
代码分享
下面分享我自己写的测试代码片段,供大家参考:
/** * <b>获取指定的URL返回的数据信息</b> * @param <font color="#efac10"><a href="http://www.baidu.com">_url:指定的URL</a></font> * @return * @throws ClientProtocolException * @throws IOException */ public String getReponse(String _url) throws ClientProtocolException, IOException { String readContent=null; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(SinaJsonTest.SinaUrl); System.out.println("0.Send the URL to Sina Sever...."); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("1.Get Response Status: " + response.getStatusLine()); if (entity != null) { System.out.println(" Get ResponseContentEncoding():"+entity.getContentEncoding()); System.out.println(" Content Length():"+entity.getContentLength()); //getResponse InputStream in=entity.getContent(); int count = 0; while (count == 0) { count = Integer.parseInt(""+entity.getContentLength());//in.available(); } byte[] bytes = new byte[count]; int readCount = 0; // 已经成功读取的字节的个数 while (readCount <= count) { if(readCount == count)break; readCount += in.read(bytes, readCount, count - readCount); } //转换成字符串 readContent= new String(bytes, 0, readCount, "UTF-8"); // convert to string using bytes System.out.println("2.Get Response Content():\n"+readContent); } return readContent; }
Java InputStream读取网络响应Response数据的方法!(重要)
标签:
原文地址:http://www.cnblogs.com/lonelyxmas/p/4638346.html