2010-09-06 66 views
0

我在Android中發現HTTP POST問題。Android中的HTTP Post問題

問題發生在代碼正在讀取響應時,它無法獲取我想要檢索的完整網頁代碼。

我只檢索一塊網頁。

下面是代碼:

try { 

     HttpClient httpclient = new DefaultHttpClient(); 

     HttpPost httppost = new HttpPost(URL); 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("text", "06092010")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     HttpResponse response; 
     response=httpclient.execute(httppost); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 


     String s = ""; 
     String line = reader.readLine(); 

     while(line != null){ 
      s += line+"\n"; 
      line = reader.readLine(); 
     } 


     Log.d("Street", "Result: "+s);   


    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block   
     Log.d("Street", e.toString()); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block   
     Log.d("Street", e.toString()); 
    } catch (Exception e) { 
     Log.d("Street", e.toString()); 
    } 

回答

0

使用你的代碼中,我得到了相同的結果,但現在我知道這個問題。

問題不在於它的代碼,是Android LogCat(記錄器)在哪裏打印生成的字符串。在這個記錄器中,如果字符串太長,它只會顯示一小段結果。

所以問題是,機器人的記錄顯示了多頭的字符串

由於燃氣公司的幫助的方式!

+0

請將此標記爲已回答,然後使用此帖作爲答案。幫助保持StackOverflow整潔! – 2010-11-08 01:44:42

0

所以reader.readLine被返回null您已到達流的末尾之前?緩衝區最後是否包含換行符? The docs表明流的末尾不構成「行尾」:

讀取一行文本。一條線被換行符('\ n'),回車符('\ r')或回車符 中的任意一個 被認爲是由一個換行符緊接。

我用這種方法我自己,它的工作原理,但不是非常有效的解決方案:

public static String URLToString(URL url) throws IOException { 
    InputStream in = (InputStream) url.getContent(); 
    int ch; 

    StringBuffer b = new StringBuffer(); 
    while((ch = in.read()) != -1){ 
     b.append((char)ch); 
    } 

    return b.toString(); 
}