【问题标题】:URLConnection receive wrong text from php serverURLConnection 从 php 服务器接收到错误的文本
【发布时间】:2016-07-19 13:41:02
【问题描述】:

我有一个有 4 个活动的应用程序。在第一个活动中,我想从我的网站(PHP 文件)请求一些文本。我第一次按下按钮来获取数据它工作正常,但在下一次按下按钮时,它返回一个正确的文本,但将它与以前的文本连接起来。参见示例:

First press: returns: "abc"
Second press: returns: "abcabc" (must be return abc)
Third press: returns: "abcabcabc" (must be return abc)
.
  1. 我每次都清除文本视图。
  2. 我每次都关闭连接。
  3. 我每次都关闭BufferedReader
  4. 我关闭了。

活动1:

try{
    URL u = new URL(uu);
    HttpURLConnection con = (HttpURLConnection) u.openConnection(Proxy.NO_PROXY);
    con.setDoOutput(true);
    con.setUseCaches(false);
    PrintStream pr = new PrintStream(con.getOutputStream());
    pr.print("code=3&arg1=" + str);
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
    String l;
    while ((l=br.readLine())!=null){
        z = z + "\n" + l;
    }
    br.close();
    pr.close();
    con.disconnect();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView tx = (TextView) findViewById(R.id.textView2);
            tx.setMovementMethod(new ScrollingMovementMethod());
            tx.setText("");
            tx.setText(z);
        }
    });
}
catch (final Exception ex){
}

【问题讨论】:

  • 在while循环前添加z="";
  • 您可能需要在获取输入之前刷新PrintStream。我会为此使用write() 而不是print()

标签: java android http httpurlconnection


【解决方案1】:

我看不到您在哪里声明了 z 字符串,但您显然是在附加它。

您应该清除它,或者为每个请求使用一个新字符串。

并使用StringBuilder。你的内存使用量会低得多。

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多