Search code examples
androidandroid-asynctaskhttp-postandroid-internet

httpPost not working android


I'm trying to send a httpPOST request to some url.This is my code. I'm using ASync Task method which i found on the net

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new MyHttpPost().execute();

}
private class MyHttpPost extends AsyncTask<String, Void, Boolean> {


        @Override
    protected Boolean doInBackground(String... arg0) 
    {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://someurl");

            try {
             // Add your data
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(4);
            nameValuePairs.add(new BasicNameValuePair("User", "abcd"));
            nameValuePairs.add(new BasicNameValuePair("email", "1234"));
            nameValuePairs.add(new BasicNameValuePair("password", "abcd"));
            nameValuePairs.add(new BasicNameValuePair("username", "1234"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
           HttpEntity httpEntity = response.getEntity();
           result = httpEntity.getContent();


            } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
            } catch (IOException e) {
             // TODO Auto-generated catch block
            }
            return true;
    }

    }



 }

I have also declared the network permissions in manifest

uses-permission android:name="android.permission.INTERNET" 
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" 

Yet after executing the application my server database isin't showing any hits. Even if i comment out the list where i'm adding my data , Even for a blank httpPost , there are no hits at all. Please Help.Urgent.All answers appreciated. Thank You


Solution

  • Try to create DefaultHTTPClient with standart parameters.

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
            HttpVersion.HTTP_1_1);
    HttpClient httpClient = new DefaultHttpClient(params);
    

    It's works fine for me.

    Also I sets the request entity with UTF-8 encoding:

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));