Post data using json Android

( 1 ) Create Android Application

  • File >> New >> Android Application
  • App Name: POST JSON
  • Enter Project Name: android-post-json
  • Pakcage:
  • Keep other defualt selections, go Next  till you reach Finish

( 2 ) The App Layout & Views

  • Main layout is LinearLayout
  • One TextView that shows connection status “the one in green”.
  • One child layout RelativeLayout holding data entry part.
  • Three TextViews “Name, Country & Twitter” baseline-aligned with their correspondingEditText
  • One Button to send “post” data to the server.
  • res/layout/activity_main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”;
    android:orientation=”vertical” >
        android:text=”is connected?” />

( 3 ) The Person Class


This is a simple model class to hold person information “name, country & twitter account”.

  • /src/com/hmkcode/android/vo/


public class Person {
    private String name;
    private String country;
    private String twitter;
//getters & setters….

( 4 ) The Activity Class

  • onCreate()
    1. Get reference to the defined views in layout file
    2. Check for connection status
    3. Add click listener to the Post button
  • POST(url, Person)
      1. Open Http connection.
      2. Create HttpPOST object passing the url.
      3. Create Person object & convert it to JSON string.
      4. Add JSON to HttpPOST, set headers & send the POST request.
      5. Get the response Inputstream, convert it to String and return it.
  • HttpAsyncTask
    1. Helps in creating the connection in a separate thread so the UI will not freeze.
  • onClick
    1. This method is executed when user click on Post button
    2. It create HttpAsyncTask object and execute it.
  • isConnected()
    1. Check if there is network connection or not
  • validate()
    1. Helper method to check that data is not empty before send the request.
  • convertInputStreamToString()
    1. Helper method to convert inputstream to String
  • src/com/hmkcode/android/

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
    TextView tvIsConnected;
    EditText etName,etCountry,etTwitter;
    Button btnPost;
    Person person;
    protected void onCreate(Bundle savedInstanceState) {
        // get reference to the views
        tvIsConnected = (TextView) findViewById(;
        etName = (EditText) findViewById(;
        etCountry = (EditText) findViewById(;
        etTwitter = (EditText) findViewById(;
        btnPost = (Button) findViewById(;
        // check if you are connected or not
            tvIsConnected.setText(“You are conncted”);
            tvIsConnected.setText(“You are NOT conncted”);
        // add click listener to Button “POST”
    public static String POST(String url, Person person){
        InputStream inputStream = null;
        String result = “”;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = “”;
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate(“name”, person.getName());
            jsonObject.accumulate(“country”, person.getCountry());
            jsonObject.accumulate(“twitter”, person.getTwitter());
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // ** Alternative way to convert Person object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader(“Accept”, “application/json”);
            httpPost.setHeader(“Content-type”, “application/json”);
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
                result = “Did not work!”;
        } catch (Exception e) {
            Log.d(“InputStream”, e.getLocalizedMessage());
        // 11. return result
        return result;
    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected())
                return true;
                return false;    
    public void onClick(View view) {
                    Toast.makeText(getBaseContext(), “Enter some data!”, Toast.LENGTH_LONG).show();
                // call AsynTask to perform network operation on separate thread
                new HttpAsyncTask().execute(“;);
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String… urls) {
            person = new Person();
            return POST(urls[0],person);
        // onPostExecute displays the results of the AsyncTask.
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), “Data Sent!”, Toast.LENGTH_LONG).show();
    private boolean validate(){
            return false;
        else if(etCountry.getText().toString().trim().equals(“”))
            return false;
        else if(etTwitter.getText().toString().trim().equals(“”))
            return false;
            return true;    
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = “”;
        String result = “”;
        while((line = bufferedReader.readLine()) != null)
            result += line;
        return result;

Note: do not forget to add the permissions to AndroidManifest.xml file

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

( 5 ) Run & Check

  • Deploy the app and run it
  • Enter name, country & twitter
  • Click on “POST” button.
  • Wait for the “Data Sent!” message

Reference :





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s