Search code examples
javaandroidhttprequestandroidhttpclient

Android POST Request to PHP


I try to develope an Android application. In this application, I need to send a POST request to a PHP page.

My code is at Java side:

 DefaultHttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://localhost/get.php");

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("mail", "asdasd"));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     try{
            HttpResponse httpresponse = httpclient.execute(httppost);

     }catch(Exception e){
         Toast.makeText(getApplicationContext(), "Didn't Happen",10).show();    
     }

Manifest.xml

 <?
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.misman"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:permission="android.permission.INTERNET"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.misman.MainActivity"
            android:label="@string/app_name" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have searched from a lot of websites and the code goes in catch block continuously.I also used HttpURLConnection and didn't work. Can you help me what can be the problem?


Solution

  • My problem was that I want to run my code in application main thread and main thread doesn't allow that. There are a few ways to solve this problem,

    1. Using AsyncTask to perform background operation
    2. Run the code in a new thread
    3. Enable network operation in MainActivity and this is what I choose for now by

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().
                                                      detectNetwork().build();
      StrictMode.setThreadPolicy(policy);
      

    UPDATE

    Because of the name of the question I want to share how to make Http call in android in order to guide people. There are some apis:

    And there is a training in