【问题标题】:Android HTTP POST to get response without JSON, and put in ToastAndroid HTTP POST 在没有 JSON 的情况下获得响应,并放入 Toast
【发布时间】:2012-12-15 17:47:23
【问题描述】:

我想测试我的 Android 应用是否可以在没有 JSON 的情况下从 php 页面成功获取响应。 php 只包含echo "hello";,但我没有吐槽它。我能找到的最接近的解决方案是,我试图将其中的一些部分放入我的代码中:How can I view the string sent from httppost?

我的代码如下(更新):

public void onClick(View v) {
    Thread t = new Thread() {
        @Override
        public void run() {
            Log.i("Threaded", "Inside thread!!!");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.10/fyp/test.php");

            try {
                HttpResponse response = httpclient.execute(httppost);
                InputStream content = response.getEntity().getContent();
                Log.i("Connect", content.toString());

                BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while ((line = buffer.readLine()) != null) {
                    sb.append(line + "\n");
                }
                Log.i("Connect", sb.toString());

                handler.post(new Runnable() {
                    public void run() {       
                        showToastMessage("hello");       
                      }
                    });
            } catch (Exception e) {
                Log.e("Connect", "Fail");
                e.printStackTrace();
            }
        }

    };
}

线程似乎没有运行,Log.i("Threaded", "Inside thread!!!"); 行没有显示在 LogCat 中,我做错了哪一部分?注意:类中已经声明了handler。

【问题讨论】:

  • 如果可以,请发布堆栈跟踪,以便我们知道错误是什么
  • “错误”是我不能敬酒“你好”,我猜答案是@Nicklas。

标签: android url http-post


【解决方案1】:

确保在 UI 线程上执行 toast,否则它将失败。 使用 Handler 或将网络操作包装在 AsyncTask 中,在其中将结果传递给由 UI 线程处理的 onPostExecute 方法。

http://developer.android.com/reference/android/os/AsyncTask.html

如果这不是您的问题,请添加日志记录以查看您是否从服务器获得响应并检查您的 LogCat 是否有“hello”

【讨论】:

  • 我想这就是问题所在,我没有使用处理程序,我将其视为接收位置数据。我尝试登录,但它没有显示任何内容,也许我错误地记录了它?我在while循环后面放了Log.i("Connect", sb.toString());,LogCat中没有出现。
  • 你能给我一个关于在这种情况下应该如何使用 Handler 的示例吗?从我浏览的代码来看,他们似乎在使用 Handler+Message+Bundle,但我不知道如何将 Bundle 与响应消息“hello”一起使用。
  • 您不需要使用消息或捆绑。使用活动线程实例化处理程序,然后使用新的 Runnable 调用 handler.post(),在 runnable 中执行 toast。完毕。 :P
  • 在您收到回复后添加日志记录,以查看您也成功发布了帖子。如果您遇到连接问题,可能需要长达 30 秒的时间才会超时并记录异常。
  • 你调用 t.start(); ?
猜你喜欢
  • 2018-11-26
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多