【问题标题】:Error with HTTP POST ConnectionHTTP POST 连接出错
【发布时间】:2012-01-06 18:52:57
【问题描述】:

我正在使用一个类来使用 HTTP POST 并通过 php/json 从数据库获取数据并将其转换为字符串。

问题是我得到 "Error in http connection android.os.NetworkOnMainThreadException" 在 LogCat 中。我正在模拟器上对此进行测试,并且使用了正确的端口地址。我知道这一点是因为该端口在应用程序的其他部分工作正常(从 Localhost 加载 HTML)。如果我在桌面浏览器中运行 php 文件,它运行良好。我也知道在 mySQL 中为 10.0.2.2 和 php 登录文件中设置的用户正确设置了权限。

所以我的问题是:有没有人遇到过同样的问题,如果有,你有没有弄清楚问题是什么,或者我应该寻找什么其他想法?

感谢您的帮助!

public void loadQuery(String p) {

        String qO = getIntent().getStringExtra("QUERY_ORDER");

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            // HttpPost httppost = new HttpPost("http://10.0.2.2/Andaero/php/" +
            // p + qO + ".php");

            //Hard coded the php link to make sure -->

            HttpPost httppost = new HttpPost(
                    "http://10.0.2.2/Andaero/php/regulatory_list_ASC.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        setListAdapter(new QueryAdapter(this, result));
    }

【问题讨论】:

    标签: php android json android-emulator http-post


    【解决方案1】:

    您似乎正在应用的主线程上执行网络操作(这是引发该异常的常见原因)。

    你不应该那样做。主线程应该只用于用户交互,所有网络交互都应该卸载到辅助线程(例如,使用 AsyncTask)。

    有关更多信息,请阅读以下内容: http://developer.android.com/guide/practices/design/responsiveness.html

    【讨论】:

    • 谢谢。你能举个例子说明如何把它放在另一个线程上吗? - 我还没有这样做。
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多