Rajeey3
Rajeey3

Reputation: 67

Sending Variables to a REST api to be saved on server

I am really struggling with this for some time now and I am really lost in terms of how this works.

I have written a REST service in netbeans and I have passed through Json data and tested that it works using Postman and it is successfully saving to the database.

Now, I want the variables in my mobile application to be sent to that REST api so that they can then be saved to the database.

I have looked at many answers on this but can get none which fully explain to me how to do this.. Ideally I am trying to POST or PUT data from my mobile app into my database.

Here is what I have tried so far:

 submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            details = editTextDetails.getText().toString();
            getCurrentDateandTime();

            String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";

            HttpClient client = new DefaultHttpClient();

            HttpPost request = new HttpPost(url);

            JSONObject params = new JSONObject();

            try {
                params.put("machinetype", machineType);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                params.put("workordernumber", workOrderNumber);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("employeename", employee);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("activity", activity);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("durationhours", durationHours);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("durationmins", durationMins);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("downtimehours", downTimeHours);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("downtimemins", downTimeMins);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            try {
                params.put("details", details);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("currentdateandtime", currentDateandTime);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            StringEntity jsonEntity = null;
            try {
                jsonEntity = new StringEntity(params.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            request = new HttpPost(url);

            request.addHeader("Content-Type", "application/json");


            request.setEntity(jsonEntity);

            try {
                HttpResponse response = client.execute(request);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
}

can someone please point me in the right direction

Thanks in advance!

Upvotes: 1

Views: 555

Answers (2)

You have an idea in how to do the post petition, but you have a couple of problems. The first and more important problem is that if you want to retrieve information from a server, you must put your code in an async task. You can't do it in UI Thread. So, i'm gonna share with you a class that implements all the logic you need and you just have to use it. First you need to use gson, look how to use it here

https://github.com/google/gson

and the code is here. It have two methods, one for GET and other for POST.

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrador on 4/27/2017.
 */

public class JsonReaderFromUrl {

    public static final int SUCCESS = 0;
    public static final int FAILED = 1;
    public static final int PROGRESS = 2;


    public interface OnJesonInterface{
        void OnJsonReceive(int status, JSONObject jsonObject, int key);
    }

    public JsonReaderFromUrl() {
    }

    public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
        new AsyncTask<Void, String, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                onJesonInterface.OnJsonReceive(PROGRESS,null,0);
            }

            @Override
            protected String doInBackground(Void... params) {
                if(android.os.Debug.isDebuggerConnected())
                    android.os.Debug.waitForDebugger();
                try {
                    URL urlJson = new URL(url);
                    HttpURLConnection connection  = (HttpURLConnection) urlJson.openConnection();
                    connection.setDoInput(true);
                    connection.setRequestProperty("Content-Type","application/json");
                    connection.setRequestMethod("POST");
                    OutputStream outputStream = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    writer.write(body);
                    writer.flush();
                    writer.close();
                    outputStream.close();
                    connection.connect();
                    StringBuilder stringBuilder = new StringBuilder();
                    int httpStatus = connection.getResponseCode();
                    if (httpStatus == HttpURLConnection.HTTP_CREATED){
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(connection.getInputStream(),"utf-8")
                        );
                        String line = "";
                        while ((line = br.readLine()) != null){
                            stringBuilder.append(line + "\n");
                        }
                        br.close();
                        return stringBuilder.toString();
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s != null){
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    onJesonInterface.OnJsonReceive(FAILED,null,0);
                }
            }
        }.execute();
    }

    public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
        AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                onJesonInterface.OnJsonReceive(PROGRESS,null,0);
            }

            @Override
            protected String doInBackground(Void... params) {
                try {
                    URL urlJson = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
                    connection.connect();

                    InputStream stream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    StringBuffer stringBuffer = new StringBuffer();
                    String line = "";
                    while ((line = reader.readLine()) != null){
                        stringBuffer.append(line + "\n");
                        Log.d("RESPONDE JSON: ",">" + line);
                    }
                    return stringBuffer.toString();



                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s != null){
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                else {
                    onJesonInterface.OnJsonReceive(FAILED,null,0);
                }
            }
        }.execute();
    }
}

import this class where you need and use it PD: The key value is an int that can be used to retrieve what response correspond to each petition, this in case you use this class with a lot of petitions.

Upvotes: 0

Rasoul Miri
Rasoul Miri

Reputation: 12222

just use retrofit 2 for connect to server. see this link

Upvotes: 1

Related Questions