Thursday 30 March 2017

How to post the data in object on server.

Example:

{
    "action": "login",   
    "email": "abc@gmail.com",
    "password": "12345"
}



Creating New Project.

Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project. 
compile 'com.android.support.constraint:constraint-layout:1.0.1'
compile 'com.loopj.android:android-async-http:1.4.9'



Create Xml file in project.    
Open => app => res => layout - activity_main.xml.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="12dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtText"
        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>


Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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 cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;


public class MainActivity extends AppCompatActivity { 
    //Button
    Button loginButton;
    //TextView
    TextView responseTextView;
    // Response
    String responseServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Getting the Widget Id Here
        init();
        //using the click leistner here
        listener();

    }

    private void init() {
        //TextView
        responseTextView = (TextView) findViewById(R.id.txtText);
        //Button
        loginButton = (Button) findViewById(R.id.sendData);
    }

    private void listener() {
        loginButton.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("Enter your url here");

            try {

                JSONObject jsonobj = new JSONObject();
                jsonobj.put("action", "login");// This field accouding to server requirment...
                jsonobj.put("email_mobile", "abc@gmail.com"); //put the email EditText field text here...
                jsonobj.put("password", "1234");//put the passwors EditText field text here...
                StringEntity stringEntity = new StringEntity(jsonobj.toString());

                httppost.setEntity(stringEntity);
                // 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);
                //Here getting the response data....

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            //set the server response here
            responseTextView.setText(responseServer);
        }
    }

    public static class InputStreamToStringExample {

        public static void main(String[] args) throws IOException {

            // intilize an InputStream
            InputStream is = new ByteArrayInputStream("file content....".getBytes());
            String result = getStringFromInputStream(is);
        }

        // 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();
        }

    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

No comments:

Post a Comment