Stack Exchange
What is wrong in my android app with HttpPost?
I'm making a new android app, when I send a values with HttpPost to my web file post.php, but it is don't working. What is it wrong ?
activity_activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".ActivityPrincipal">

</RelativeLayout>

ActivityPrincipal.java
package com.pixelayer.httppost.httppostandroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class ActivityPrincipal extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_principal);

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost("www.mysite.com/post.php"); //
    replace with
    // your url

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);

    nameValuePair.add(new BasicNameValuePair("nome", "test_user"));

    nameValuePair.add(new BasicNameValuePair("site", "testeandroid"));

    // Encoding data

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    // making request

    try {
        HttpResponse response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pixelayer.httppost.httppostandroid" >

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ActivityPrincipal"
        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>

Thank you so much

What do mean with "is don't working"?

Can you describe how it's not working?

My app android don't run. it stop anytime.

You are doing this HTTP request in main thread, if you look your logcat you can see that it's not allowed.
You should use the AsyncTask to do it or a library (like Volley or Loopj).
To force Android to performe this you must change the StrictMode policy (insert this code before HTTP request)
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);

AsyncTask example
private class HTTPTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      ...Performe your request
      return response;
    }

@Override
protected void onPostExecute(String result) {
  .../Use response
}

}
To call...
HTTPTask task = new HTTPTask();
task.execute(new String[] { "http://www.url.com" });

For Loopj there is a Doc http://loopj.com/android-async-http/
For Volley https://developer.android.com/training/volley/index.html

Please, Could you be to take a example for me ?

create a class extending AsyncTask , override methods doInBackground , onPostExecute. To launch your goal call theAsyncTaskInstance.execute(param_values_separated_by_comma); The action is inside the doInBackground :)

My new ActivityPrincipal.java
It is code is correct now ?
package com.pixelayer.httppost.httppostandroid;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class ActivityPrincipal extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_principal);

    TextView t = (TextView)findViewById(R.id.textViewPost);
    new TheTask().execute("mysite.com/post.php");
}

class TheTask extends AsyncTask<String,Void,String>
{

    @Override
    protected String doInBackground(String... arg0) {
        String text =null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(arg0[0]);
            HttpResponse resp = httpclient.execute(httppost);
            HttpEntity ent = resp.getEntity();
            text = EntityUtils.toString(ent);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return text;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        TextView t = (TextView)findViewById(R.id.textViewPost);
        t.setText(result);
    }

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_activity_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

