0

我一直在努力将 JSON 对象从 android 上的应用程序发送到 php 文件(本地托管)。php 位与我的问题无关,因为wireshark 没有记录我的应用程序中的任何活动(eclipse/ADK 中的仿真),而且几乎可以肯定与我的发送方法有关:

      try {
        JSONObject json = new JSONObject();
        json.put("id", "5");
        json.put("time", "3:00");
        json.put("date", "03.04.12");
        HttpParams httpParams = new BasicHttpParams();
        HttpClient client = new DefaultHttpClient(httpParams);
        //
        //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
        //             "json={\"UserName\":1,\"FullName\":2}";
        String url = "http://localhost/datarecieve.php";

        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                "UTF8")));
        request.setHeader("json", json.toString());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        if (entity != null) {
            InputStream instream = entity.getContent();

        }
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }

我已经根据我找到的一个示例对其进行了修改,所以我确信我已经采用了一些非常好的代码并对其进行了修改。我了解多线程的要求,因此我的应用程序不会挂起和死机,但不确定它的实现。使用 Asynctask 会解决这个问题,还是我错过了其他重要的事情?

感谢您提供任何帮助。

4

2 回答 2

1

您应该使用 asynctask 或线程,因为在更高版本的 android 中,它不允许长时间运行的任务,例如来自 ui 线程的网络操作。

这是更多描述的链接

于 2013-01-24T05:50:01.663 回答
1

假设您使用模拟器来测试代码,localhost指的是模拟环境。如果需要访问自己电脑上托管的php,需要使用IP 10.0.2.2或者局域网IP如192.168.1.3。检查从模拟环境中引用本地主机

您可以参考保持您的应用响应以了解有关在AsyncTask中运行长时间运行的操作

于 2013-01-24T06:45:32.580 回答