Last updated on January 8th, 2020 at 10:03 pm

You can use Volley Library to send data to server please Check this Post:- Send data to the server using Volley.

 

 

In this post i explain you how we can POST JSON data to server in android. There are no of ways through which we can send data to server. In this i also explain how we can handle incoming JSON data on server. This simple and easiest way to send data to server i am not using any extra library for this.

Step 1. Create new project in Android Studio/ Eclipse.

Step 2. Open your activity_main.xml inside layout folder and add the following code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/raw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/sendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send data" />
</LinearLayout>

And also Don’t forget to add internet permission to your AndroidManifest.xml

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

 Step 3. Now open your MainActivity.java in side java folder and add bellow code. In this code we post data to server i am using POST method and create post variable/key {req}  inside this i put JSON note i convert my JSON to string so it will transfer to string.

package com.senddatatoserver;
 
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
 
public class MainActivity extends ActionBarActivity {
 
    Button bt;
    TextView txt;
 
    // Response
    String responseServer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        txt = (TextView) findViewById(R.id.raw);
        bt = (Button) findViewById(R.id.sendData);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncT asyncT = new AsyncT();
                asyncT.execute();
            }
        });
    }
 
    /* Inner class to get response */
    class AsyncT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("<YOUR_SERVICE_URL>");
 
            try {
 
                JSONObject jsonobj = new JSONObject();
 
                jsonobj.put("name", "Aneh");
                jsonobj.put("age", "22");
 
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
 
                Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
 
              // Use UrlEncodedFormEntity to send in proper format which we need
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 
                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                InputStream inputStream = response.getEntity().getContent();
                InputStreamToStringExample str = new InputStreamToStringExample();
                responseServer = str.getStringFromInputStream(inputStream);
                Log.e("response", "response -----" + responseServer);
 
 
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
 
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
 
            txt.setText(responseServer);
        }
    }
 
    public static class InputStreamToStringExample {
 
        public static void main(String[] args) throws IOException {
 
            // intilize an InputStream
            InputStream is =
                    new ByteArrayInputStream("file content..blah blah".getBytes());
 
            String result = getStringFromInputStream(is);
 
            System.out.println(result);
            System.out.println("Done");
 
        }
 
        // convert InputStream to String
        private static String getStringFromInputStream(InputStream is) {
 
            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();
 
            String line;
            try {
 
                br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
 
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return sb.toString();
        }
 
    }
}

Step 4. Now when we receive data at server end we need to get object. I am using PHP to get this data.

<?php
$get = json_decode(stripslashes($_POST['req']));
// Get data from object
$name = $get->name; // Get name you send
$age = $get->age; // Get age of user

// Your code.....

Done.  🙂