【问题标题】:Problem with HTTP Post in AndroidAndroid中的HTTP Post问题
【发布时间】:2010-09-06 18:28:14
【问题描述】:

我在 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());
    }

【问题讨论】:

    标签: html android http post httpclient


    【解决方案1】:

    使用您的代码,我得到了相同的结果,但现在我知道问题所在了。

    问题不在于代码,而在于我打印结果字符串的 Android LogCat(记录器)。在这个记录器中,如果字符串太长,它只会显示一小部分结果。

    所以问题是android的记录器显示长字符串的方式

    感谢 Gaz 的帮助!

    【讨论】:

    • 请将此标记为已回答,然后使用此帖子作为答案。帮助保持 StackOverflow 整洁!
    【解决方案2】:

    所以 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2015-08-11
      相关资源
      最近更新 更多