连接webservice时出错

时间:2012-03-30 11:42:26

标签: android httpconnection

我在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

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

请参阅以下链接以了解事件线程和网络任务实现:

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

从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();