0
votes

I have refere this ... Android HttpClient, DefaultHttpClient, HttpPost , http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient and http://www.javacodegeeks.com/2013/06/android-apache-http-client.html link... They have specify to pass url and they have not specify to pass parameter ... When i implement the code given in above url I get this error ... I am new to this .. I call this method...

   public void postData() {
    String res="";
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

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

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        Log.e("response",""+response);


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

} 

Please help me... Thanks..

1
Please share you code and the error you get - Hannoun Yassir
Thanks for quick reply..I post my code.. please have a look.. - ADT

1 Answers

1
votes

Since you did not include the error i would assume it is because you are blocking the UI thread which works fine on old version of android but the in the latest versions you will have to use an AsyncTask to do your post request.

private class MyPostTask extends AsyncTask<URL, Void, Void> {
     protected Long doInBackground(URL... urls) {
         String res="";
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(urls.get(0));

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

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.e("response",""+response);


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

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

to make the request:

new MyPostTask().execute("http://example.com/foo/bar/");