1. java.lang.IllegalStateExceptio n: Content has been consumed
这个问题是多次调用httpEntity.getContent()导致的, entity中的内容只能读取一次, 参考如下:
You can retrieve the content from the entity only once. If you have
already extracted the content somewhere, and you try to fetch it
again, it will throw this IllegalStateException. Check you code and
make sure that you make this call only once.
2. http header 中的content-length
这个问题导致了各种千奇百怪的error,反正就无法返回数据。
比如; source not found, Runtime Exception等等问题,其实问题出现在测试服务器上的Nignx的返回头部没有包含Firebug这项信息,所用通过代码
int length = ( int ) httpEntity.getContentLength(); 获得的是 -1, 而后所有通过length设置的长度都自然出错哦。
可以参考详细说明: Android-app-failed-to-get-content-at-80-port-with-httpclient/7050034#7050034
与此相关的,可以了解一下, http chunked 编码。
可以用 Firebug or httpwatch
代码类似:
String url3000 = "http://192.168.1.103:3000/posts.xml";
String url = "http://192.168.1.103/posts.xml";
Log.d( "posts", "performing get " + url);
HttpGet httpGet=new HttpGet(url);
HttpResponse responsep=httpClient.execute(httpGet);
System.out.println(responsep.getStatusLine());
HttpEntity httpEntity = responsep.getEntity();
int length = ( int ) httpEntity.getContentLength();
System.out.println("The content length is: "+length);
Log.d( "posts", "The content length is: " + length );
StringBuffer sb = new StringBuffer( length );
InputStreamReader isr = new InputStreamReader( httpEntity.getContent(), "UTF-8" );
char buff[] = new char[length];
int cnt;
while ( ( cnt = isr.read( buff, 0, length - 1 ) ) > 0 )
{
sb.append( buff, 0, cnt );
System.out.println("The content is: "+sb.toString());
}
System.out.println("The content is: \n"+sb.toString());
Log.d( "posts", "The content is: " + sb.toString() );
isr.close();