0

I am creating an HTTP client to execute a PHP file in my server and this is the code:

try
{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://yasinahmed.cpa10.com/sendnoti.php");
    HttpResponse response = httpclient.execute(httppost);

    Toast.makeText(GCMMainActivity.this, "Done", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
    Toast.makeText(GCMMainActivity.this, "error", Toast.LENGTH_LONG).show();
}

Many times I used this code and it's working without a problem, but this time when I execute the code it always go to the exception and prints the error. This time, I used AVD with Google API level 17, so is this the problem or is there another problem in the code?

4

2 回答 2

1

当应用程序尝试在其主线程上执行网络操作时,将引发此异常。在 AsyncTask 中运行您的代码:

class Preprocessing extends AsyncTask<String, Void, Boolean> {

    protected Boolean doInBackground(String... urls) {
        try
        {
           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://yasinahmed.cpa10.com/sendnoti.php");
           HttpResponse response = httpclient.execute(httppost);  
           return true;      
       }
       catch(Exception e)
      {        
           return false;
      }
    }
    protected void onPostExecute(Boolean result) {
        if(result)
            Toast.makeText(GCMMainActivity.this, "Done", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(GCMMainActivity.this, "error", Toast.LENGTH_LONG).show();
    }
}

在您的活动中调用此类:

new Preprocessing ().execute();

不要忘记将其添加到 AndroidManifest.xml 文件中:

<uses-permission android:name="android.permission.INTERNET"/>
于 2013-07-22T17:58:19.237 回答
0

这将有助于了解错误。但由于我必须猜测,我敢打赌,您正试图在主事件线程(也称为 UI 线程)上执行此代码。这总是错误的,从 API 级别 11 开始,它会导致 aNetworkOnMainThreadException被抛出。有关在 Android 中处理网络的正确方法,请参阅文档为响应性而设计。

于 2013-07-22T17:53:49.467 回答