Sunday, January 26, 2014

Sending via POST request in android

http://www.wikihow.com/Execute-HTTP-POST-Requests-in-Android
http://www.vogella.com/tutorials/ApacheHttpClient/article.html

http://www.onlymobilepro.com/2013/03/16/submitting-android-form-data-via-post-method/

public void send(View v)
        {
            //get message from message box
            String  msg = msgTextField.getText().toString();
             
            //check whether the msg empty or not
            if(msg.length()>0) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
                 
                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                       nameValuePairs.add(new BasicNameValuePair("id", "01"));
                       nameValuePairs.add(new BasicNameValuePair("message", msg));
                       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                       httpclient.execute(httppost);
                        msgTextField.setText(""); //reset the message text field
                        Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //display message if text field is empty
                Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
            }
        }
         
    }

>>>>Using above method I got an exception that with Fatal error ,cannot execute an activity at line httpclient.execute(..) so I figured other way to do it..Remember following points
-Since http request uses network related connections it should be done in background using AsyncTask and write all your codes inside class extending AsyncTask ..see link below
-code belo worked for me to send Http get request..

http://theopentutorials.com/tutorials/android/http/android-how-to-send-http-get-request-to-servlet-using-httpurlconnection/
sample code to call these functions:
CustomHttpClient task = new CustomHttpClient();
String url = "http://192.168.1.157/gcmserver/register.php?name=abcd&email=a@a.de&regID=" + registrationID;
             task.execute(new String[] { url });
--------------------------------------------
package com.example.helloandroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;

public class CustomHttpClient extends AsyncTask<String,String,String> {

    @Override
    protected String doInBackground(String... urls) {
        String output = null;
        for (String url : urls) {
            output = getOutputFromUrl(url);
        }

        return null;
    }

    private String getOutputFromUrl(String url) {
        StringBuffer output = new StringBuffer("");
        try {
            InputStream stream = getHttpConnection(url);
            BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(stream));
            String s = "";
            while ((s = buffer.readLine()) != null)
                output.append(s);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return output.toString();
       
    }
   
    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
   
}


No comments:

Post a Comment