https://www.quora.com/How-do-I-send-data-to-a-Node-js-server-from-an-Android-app


Suppose you want to send a var called “name” (A JAVA variable) from your Android App to your Node server.

First create a route on node server to handle the request (POST request more specifically). Note that I am using express to write less code here.

Suppose you want to make a request via the URL http://mynodeapp.xyz/route1/

So define this route as:

  1. var express = require('express');
  2. var app = express();
  3.  
  4. app.post('/route1', function (req, res) {
  5. var post=req.body;
  6. console.log("Received variable : "+ post.name);
  7. res.send("Sending some message);
  8. });

The variable post will have all the variables passed to it from your android activity. If you want to send some response message from the server you can use res.send().

Now to send the var “name” from Android Activity you may use Android’s built in AsyncTask Class. This helper class allows you to perform background operations.

Inside your Activity define a background class which extends AsyncTask Class and does the required task of sending the data to node server.

Something like

  1. class BackgroundWorker extends AsyncTask<String> {
  2. public BackgroundWorker(Context ctx){
  3. context=ctx;
  4. }
  5. @Override
  6. protected String doInBackground(String... params) {
  7. String name = params[0];
  8. String myurl = "http://mynodeapp.xyz/route1/";
  9. try{
  10. URL url = new URL(myurl);
  11. HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection(); httpURLConnection.setRequestMethod("POST");
  12. httpURLConnection.setDoOutput(true);
  13. httpURLConnection.setDoInput(true);
  14. OutputStream outputStream = httpURLConnection.getOutputStream();
  15. BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  16. String post_data = URLEncoder.encode("name","UTF-8");
  17. bufferedWriter.write(post_data);
  18. bufferedWriter.flush();
  19. bufferedWriter.close();
  20. outputStream.close();
  21. InputStream inputStream = httpURLConnection.getInputStream();
  22. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
  23. String result="";
  24. String line="";
  25. while((line = bufferedReader.readLine())!= null)
  26. result += line;
  27. bufferedReader.close();
  28. inputStream.close();
  29. httpURLConnection.disconnect();
  30. return result;
  31. } catch (MalformedURLException e) {
  32. e.printStackTrace();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. @Override
  38. protected void onPreExecute() {
  39. }
  40. @Override
  41. protected void onPostExecute() {
  42. }
  43. @Override
  44. protected void onProgressUpdate(Void... values) {
  45. super.onProgressUpdate(values);
  46. }
  47. }
  48. BackgroundWorker backgroundWorker=new BackgroundWorker(this);
  49. backgroundWorker.execute(name);

You may show some progress bars or dialog boxes in onPreExecute() oonPostExecute() . Also you will need to import proper classes in this android activity.

I hope it shows you the way how to send data to some server from Android.

Google it where you stuck and

Keep Coding !

Baalateja Kataru

The most popular way that clients communicate with servers is using the HTTP protocol. And since you want to send data to a server, a HTTP POST request is what you need.

There are two ways to do this, either using the HttpURLConnection class or using the HTTP library for Android called Volley. I’ll be using the latter here.

First, if you’re running Express - set up routing to handle the post requests that your server is going to recieve:

  1. var express = require('express');
  2. var app = express();
  3.  
  4. const bodyParser = require('body-parser');
  5. var server = app.listen(3000);
  6.  
  7. app.use(bodyParser.json());
  8. app.use(bodyParser.urlencoded({ extended: true }));
  9.  
  10. app.post('/postdata', (req, res) => {
  11. var data = req.body.data; // your data
  12. // do something with that data (write to a DB, for instance)
  13. res.status(200).json({
  14. message: "Data received successfully"
  15. });
  16. });

Next, you need to write a Volley POST request in an Activity that sends data in JSON format, because that is the ideal way of communication with a RESTful Node server. In Android Studio it’s done like this:

  1. public class MainActivity extends AppCompatActivity {
  2. Button RequestButton; // button which on clicking, sends the request
  3. TextView DisplayText; // a text field to display the request response
  4. TextView DataField; // a text field where the data to be sent is entered
  5.  
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_main);
  10.  
  11. RequestButton = (Button) findViewById(R.id.RequestButton);
  12. DataField = (TextView) findViewById(R.id.DataField);
  13. DisplayText = (TextView) findViewById(R.id.DisplayText);
  14.  
  15. final RequestQueue queue = Volley.newRequestQueue(this);
  16. final String url = "http://serverdomainorip/postdata"; // your URL
  17. queue.start();
  18. RequestButton.setOnClickListener(new View.OnClickListener() {
  19. @Override
  20. public void onClick(View v) {
  21. HashMap<String, String> params = new HashMap<String,String>();
  22. params.put("data", DataField.getText().toString()); // the entered data as the body.
  23.  
  24. JsonObjectRequest jsObjRequest = new
  25. JsonObjectRequest(Request.Method.POST,
  26. url,
  27. new JSONObject(params),
  28. new Response.Listener<JSONObject>() {
  29. @Override
  30. public void onResponse(JSONObject response) {
  31. try {
  32. DisplayText.setText(response.getString("message"));
  33. } catch (JSONException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }, new Response.ErrorListener() {
  38. @Override
  39. public void onErrorResponse(VolleyError error) {
  40. DisplayText.setText("That didn't work!");
  41. }
  42. });
  43. queue.add(jsObjRequest);
  44. }
  45. });
  46. }
  47. }

Essentially, the above code takes the data entered in a text field and sends it as the body of a POST request to your node server on clicking a button on the page. Once the response is received, it sets that response as the text of another text field on the page for you to see it. Here, The data is sent as JSON by wrapping it in a JSON object and the response received is also in JSON format.