user2597622
user2597622

Reputation: 135

Creating an HTTP connection via Android

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?

Upvotes: 0

Views: 99

Answers (2)

Jainendra
Jainendra

Reputation: 25143

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in 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();
    }
}

Call this class in your Activity:

new Preprocessing ().execute();

Don't forget to add this to AndroidManifest.xml file:

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

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

It would help to know the error. But since I have to guess, my bet is that you are trying to execute this code on the main event thread (a.k.a. the UI thread). That was always wrong and as of API level 11, it will cause a NetworkOnMainThreadException to be thrown. See the document Designing for Responsiveness for the proper way to handle networking in Android.

Upvotes: 0

Related Questions