Skip to content Skip to sidebar Skip to footer

Android Http Post Request On Clicking Button

i want to send an HTTP post request by Clicking on Button to my website. i searched allot only found this piece of code // Create a new HttpClient and Post Header HttpClient httpc

Solution 1:

use AsyncTask for Performing Network Opertion on Button Click as:

publicclassonbuttonclickHttpPostextendsAsyncTask<String, Void, Void> {
    @OverrideprotectedStringdoInBackground(String... params) {
        byte[] result = null;
        String str = "";
       // Create a new HttpClient and Post HeaderHttpClient httpclient = newDefaultHttpClient();
        HttpPost httppost = newHttpPost("http://www.yoursite.com/script.php");

        try {
                // Add your dataList<NameValuePair> nameValuePairs = newArrayList<NameValuePair>(2);
                nameValuePairs.add(newBasicNameValuePair("id", "12345"));
                nameValuePairs.add(newBasicNameValuePair("stringdata", "AndDev is Cool!"));
                httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post RequestHttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = newString(result, "UTF-8");
            }
          } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }  
        return str;
    }

    /**
     * on getting result
     */@OverrideprotectedvoidonPostExecute(String result) {
        // something with data retrieved from server in doInBackground
    }
}

and on Button Click Start AsyncTask onbuttonclickHttpPost as:

buttonclick.setOnClickListener(newView.OnClickListener()
        {
         publicvoidonClick(View v) {
         new onbuttonclickHttpPost.execute(null);

     }
      });

Solution 2:

Try this...its from my working project

I have used Thread and NameValuePair to execute this.....

public String postData(String url, String xmlQuery) {

        finalStringurlStr= url;
        finalStringxmlStr= xmlQuery;
        finalStringBuildersb=newStringBuilder();

        Threadt1=newThread(newRunnable() {

            publicvoidrun() {

                HttpClienthttpclient=newDefaultHttpClient();

                HttpPosthttppost=newHttpPost(urlStr);

                try {

                    List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(newBasicNameValuePair("xml", xmlStr));

                    httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));

                    HttpResponseresponse= httpclient.execute(httppost);

                    Log.d("Vivek", response.toString());

                    HttpEntityentity= response.getEntity();
                    InputStreami= entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReaderisr=newInputStreamReader(i);

                    BufferedReaderbr=newBufferedReader(isr);

                    Strings=null;

                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }

                    Log.d("Check Now", sb + "");

                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } /*
                 * catch (ParserConfigurationException e) { // TODO
                 * Auto-generated catch block e.printStackTrace(); } catch
                 * (SAXException e) { // TODO Auto-generated catch block
                 * e.printStackTrace(); }
                 */
            }

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Getting from Post Data Method " + sb.toString());

        return sb.toString();
    }

Post a Comment for "Android Http Post Request On Clicking Button"