2014-02-24 85 views
0

對不起,我的英文。我有這個問題:當我使用httpclient時,我不能從服務器獲得完整的消息。這是我的代碼:httpclient android not full message

    DefaultHttpClient hc = new DefaultHttpClient(); 
        HttpPost postMethod = new HttpPost(params[0]); 

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.length-1); 
        for(int i=1;i<params.length;i++){ 
        int endF=params[i].indexOf("="); 
        nameValuePairs.add(new BasicNameValuePair(params[i].substring(0, endF), 
          params[i].substring(endF+1, params[i].length()))); 
        } 

        // Url Encoding the POST parameters 
        try { 
         postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        } catch (UnsupportedEncodingException e) { 
         // writing error to Log 
         e.printStackTrace(); 
        } 



       try { 

        HttpResponse resp = hc.execute(postMethod); 
        BufferedReader in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); 

        StringBuffer sbuffer = new StringBuffer(""); 
        String line = ""; 

        while ((line = in.readLine()) != null) { 
         sbuffer.append(line + "\n"); 
        } 
        in.close(); 

        response = sbuffer.toString(); 

而我得到的JSON甚至不會被「}」關閉。簡單它被切斷了。下一部分在哪裏?以及我如何獲得它?

+0

您好,歡迎堆棧溢出!你有沒有考慮切換到'HttpURLConnection'?這是谷歌推薦的Gingerbread和:http://android-developers.blogspot.com.es/2011/09/androids-http-clients.html – atxe

回答

0

嘗試這樣做的,如果它不工作,你有可能在服務器端的一些錯誤。

final HttpClient httpclient = new DefaultHttpClient(); 
final HttpPost httppost = new HttpPost("http://www.yourdomain.com/service.php"); 

try { 
    // ... Leave the post send part untouched ... 

    InputStream ips = response.getEntity().getContent(); 
    BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8")); 
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 
    try { throw new Exception(response.getStatusLine().getReasonPhrase()); } 
    catch (Exception e) { e.printStackTrace(); } 
    } 

    String s; 
    StringBuilder sb = new StringBuilder(); 

    while (true) { 
    s = buf.readLine(); 
    if (s == null || s.length() == 0) 
     break; 
    sb.append(s); 
    } 

    buf.close(); 
    ips.close(); 

    Log.d("yourTag", "Post response: " + sb.toString()); 
} 
catch (ClientProtocolException e) { e.printStackTrace(); } 
catch (IOException e) { e.printStackTrace(); } 
+0

不幸的是,它沒有幫助。服務器可以給我發送第二個http數據包的下一部分嗎因爲服務器是vk.com(它在俄羅斯就是facebook.com),我認爲這個問題不在其中。 – user1723955

+0

沒關係。我明白了這臺服務器的工作原理。謝謝! – user1723955

相關問題