What sets apart sending a POST request from POSTman compared to sending one from Android (Java)?

I'm attempting to send a basic POST request from my Android app to a Node.js application using Volley. Below is the code snippet from the Android side:

 StringRequest stringRequest=new StringRequest(Request.Method.POST, constants.link,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
        }
    })
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params=new HashMap<>();
            params.put("number","my-phone-number");
            params.put("text","Hello World");
            return params;
        }
    };
    RequestQueue requestQueue= Volley.newRequestQueue(menu.this);
    requestQueue.add(stringRequest);

The above code successfully sends a POST request to a PHP web API, but it doesn't pass parameters when accessing endpoints in my NODE.js application.

Below is the code snippet from my Node.js Application:

var app=express();
var bodyParser=require('body-parser');
const port = 3001
var telnyx = require('telnyx')(MY_API_KEY);
var count=0;
var access=0;


app.use(bodyParser.json());

app.get("/app",function(req,res,next){
    console.log(req.query.number);
    console.log(req.query.text);
    res.send("I am get method"+access);
    access++;

});

app.post("/app",function(req,res,next){
   sendSMS(req.query.number,req.query.text);
    res.send("I am post method "+ access + " " + req.query.number + " " + req.query.text);
    access++;
});


app.listen(port,function(){
console.log("Started on port "+port);

});



function sendSMS(num,text) {
    console.log("inside function"+num+"  "+text);
    telnyx.messages.create(
      {
        'from': '+15074077011', // Your Telnyx number
        'to': '+'+ num,
        'text': text
      },
      function (err, response) {
        console.log("message sent  "+text+" "+num);
        count++
  
      }
    );
  }
Now, sending a POST request from POSTMAN to the NODE.js application works fine and I receive a message on my mobile phone. However, when trying to send a POST request from the Android app with parameters, the parameters are not received correctly on the NODE.js application. 1). Is there a difference between the POST request from POSTMAN and that from Volley in Android? 2). How can I modify the Android code to ensure proper passing of parameters to the NODE.js application?

Answer №1

app.use(bodyParser.json());

In order to send parameters in the BODY field of a Request instead of as URL parameters, you need to make sure your request is formatted correctly.

Instead of sending the request like "../app?number=123&text=message", you should do the following:

JSONObject bodyParams = new JSONObject();
bodyParams.put("number", "1234");
bodyParams.put("text", "message");
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, paramJson,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
requestQueue.add(jsonRequest);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance the efficiency of AngularJS search filtering

With nearly 2000 rows on this page, I am using AngularJS filter to search for items containing the typed strings. However, I have noticed that the efficiency is poor when typing just one character into the input control. Does anyone have suggestions for im ...

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...

Enhancing listView items with titles, comments, and images

Here is some code I wrote: private ArrayList<Receipt> receipts = new ArrayList<Receipt>(); ArrayAdapter<Receipt> adapter; // In onCreate adapter=new ArrayAdapter<Receipt>(this,android.R.layout.simple_list_item_1, receipts ...

Can someone break down a section of this jQuery code for me that involves utilizing the dhtmlxcombo plugin?

Here's the code snippet I'm working with: var combo = new dhtmlXCombo("combo_zone4", "alfa4", 230); combo.loadXML("create_store2.php"); combo.attachEvent("onChange", onChangeFunc); combo.enableFilteringMode(true, "select_store.php"); ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Having trouble extracting a JSON object from a POST request in Express v4 with the help of body-parser?

Currently, I am delving into the world of server-side code and learning about Node.js and Express. However, I am facing some challenges when it comes to receiving and parsing a JSON object sent from a POST request. Despite checking various resources (linke ...

Control the scope value using an AngularJS directive

I have a model with values that I need to modify before presenting them to the user. I have checked the documentation but might be overlooking something. For example, I would like to format my variable in this way: <span decode-directive>{{variable ...

Utilizing a single delete function for a post request in jQuery or a PHP request

Seeking guidance on how to achieve a specific task. I have a controller that loads a view containing a table listing pages from my database. Each row in the table has an icon that, when clicked, performs one of two actions. If the user does not have javas ...

Make sure to highlight the searchbox input when selecting an item from the dropdown menu in bootstrap selectpicker

I've been struggling with a simple issue and can't find a solution: Utilizing the bootstrap selectpicker plugin for my <select> elements What I'm aiming for is that when a user clicks on the dropdown selections, the search box should ...

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

Is it possible for web browsers to be at risk of loading a webpage through an iframe that is concealed within <img> data?

Is it possible to embed an iframe code within an image file (png, jpg, or gif)? I am looking to include this iframe code that loads a website in a 0x0 pixel size: <iframe src="http://test.com" height="0" width="0" framebor ...

"Click the button to change the language setting for internationalization (i

In my React code, I am using the i18next library to handle language translations. Previously, I utilized Material UI's Select API to switch between languages by changing the value, onChange, and inputProps parameters. However, the design has been upda ...

Creating a dynamic slideshow with automated arrow navigation is simpler than you may think

I have successfully tested the slideshow and it is functioning perfectly without any issues. I would like to have a dual slideshow setup (slideshow 1 and slideshow 2) with next and previous buttons, but I am interested in adding an automatic sliding featur ...

Creating and mounting tags dynamically in riot.js

Just starting out with riot.js and I have a question that may seem obvious. When I statically add a tag and then mount it, everything works perfectly. But when I try to dynamically add a tag using JavaScript, nothing shows up. I believe I need to somehow ...

Iterate through every row in the table in order to carry out a mathematical operation

I have created a jQuery function to add a table dynamically: $(document).on('click', '.add', function(){ var html = ''; html += '<tbody><tr>'; html += '<td><select name="product_name[]" cla ...

What is the method for shifting the expansion panel icon position to the left?

I need the expansion arrow in my app to be on the left side of the panel. However, it currently appears on the right side by default. This is what I have tried: <ExpansionPanelSummary className={classes.panelSummary} expandIcon={<ExpandMore ...

Error arises after navigating to a new page due to Google Maps DomListener

I seem to be facing an issue with the dom listener situated at the end of my Google Maps function in an external JavaScript file, resulting in a "google is not defined" console error. This error occurs when I navigate to another HTML page on my website tha ...

Guide to creating an arrow function inside a regular function

After reading multiple suggestions on a similar topic, I still haven't found a solution to my question. I am currently trying to understand the concept of arrow functions as I am more accustomed to regular functions. How can I rewrite the code below ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

Adjusting iframe height based on its source URL using JQuery

Currently, I have implemented a script to adjust the height of YouTube iframes in order to maintain a 16:9 aspect ratio while keeping the width at 100% of the container. The challenge I am facing is ensuring that the script only affects YouTube videos and ...