【问题标题】:Error while connecting with webservice连接网络服务时出错
【发布时间】:2012-03-30 11:42:26
【问题描述】:

我在 main.java 中写了这段代码

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        try{
             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost("http://way2tutorial.com/json/index.php");
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
             HttpResponse response = httpclient.execute(httppost);
             HttpEntity entity = response.getEntity();
             InputStream is = entity.getContent();
             }catch(Exception e){
                 Log.e("log_tag", "Error in http connection"+e.toString());
            }

还包括

<uses-permission android:name="android.permission.INTERNET"/>

在清单文件中

但是在http中运行android应用程序报错

connectionandroid.os.NetworkOnMainThreadException

【问题讨论】:

标签: android httpconnection


【解决方案1】:

从 Honeycomb (v 3.0) 开始,您不能在主线程上执行网络任务。尝试在 AsyncTask 上执行此操作,或者如果您确实在执行一些琐碎的任务,请尝试将清单中的 minsdkversion 更改为低于 11。

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

【讨论】:

    【解决方案2】:

    您无法通过网络在应用程序的主线程上执行任何操作。您必须在新线程中运行它,我建议在 AsyncTask 中执行它。看这里的例子 - http://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

      【解决方案3】:

      此错误是因为您正在事件线程中执行网络任务。新的 SDK 版本强制开发人员在事件线程之外的其他线程中执行网络任务。要解决此问题,请为此创建一个单独的线程,

      Handler 和 AsyncTask 是在 EventThread 之外的其他线程中处理这些类型任务的方法,

      查看以下链接以了解事件线程和网络任务实现:

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

      http://www.vogella.de/articles/AndroidPerformance/article.html

      【讨论】:

        【解决方案4】:

        从 Honeycomb 开始,即 3.0 you are no longer allowed to do network operations in application's main thread。您应该创建一个单独的线程来执行网络操作。请尝试以下代码:

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        new Thread()
        {
            public void run()
            {
                try
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://way2tutorial.com/json/index.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                }
                catch(Exception e)
                {
                    Log.e("log_tag", "Error in http connection"+e.toString());
                }
            }
        }.start();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-05
          相关资源
          最近更新 更多