Android 通过httpclient 调用碰到的问题总结

问题一:

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设置的长度都自然出错哦。

可以参考详细说明: http://stackoverflow.com/questions/7049937/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();       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值