Android 通過httpclient 呼叫碰到的問題總結

l_serein發表於2013-05-12

問題一:

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();       

相關文章