1

I am trying to send data (POST request) from android app using retrofit2 library and receive it on the server which is written in nodejs (using express framework) but i am not able to retrieve the data which is sent from the the app.

I used retrofit with GsonConverterfactory and sent a POST request to "/temp" route.

Index.js (handles route requests):-

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use('/public',express.static('public'));

app.post("/temp",function(req,res){
    console.log(req.body);
    obj = {
        orgName : "Got the message ",
        address : "on the server"
    }
    res.json(obj);
})

app.listen(8000,function(){
    console.log("Server Started at port 8000");
})

Shop.java

package com.example.myapplication;
public class Shop {
    private String orgName;
    private String address;

    public Shop(String orgName, String address) {
        this.orgName = orgName;
        this.address = address;
    }

    public String getOrgName() {
        return orgName;
    }  

    public String getAddress() {
        return address;
    }
}

ShopApi.java

package com.example.myapplication;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;

public interface ShopApi {
    @POST("temp")
    Call<Shop> create(@Body Shop shop);
}

postData() - Method to post data from MainActivity.java

public void postData(View view){
    String BASE_URL = "http://10.0.2.2:8000/";
    String org = orgName.getText().toString();
    String address = add.getText().toString();
    //Toast.makeText(getApplicationContext(),org+" "+address,Toast.LENGTH_SHORT).show();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    ShopApi shopApi = retrofit.create(ShopApi.class);
    Shop shop = new Shop(org,address);
    Call<Shop> shopCall = shopApi.create(shop);
    shopCall.enqueue(new Callback<Shop>() {
        @Override
        public void onResponse(Call<Shop> call, Response<Shop> response) {
            if(!response.isSuccessful()){
                Toast.makeText(getApplicationContext(),response.code(),Toast.LENGTH_LONG).show();
            }
            Shop shopResponse = response.body();
            String content = shopResponse.getOrgName() + shopResponse.getAddress();
            Toast.makeText(getApplicationContext(),content,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<Shop> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });
}

A json object is expected in the req.body which should be printed in terminal but this gets printed :-

Server Started at port 8000
{}

Please help me to retrieve data on sever.

1 Answers1

0

I don't work in Node.js still I try to answer your question.

You're expecting a JSON object in server like below,

{
   "orgName": "Organization name",
   "address": "Organization address"
}

Okay, your Android part (Retrofit api interface) is correct. In run-time it produces the expected JSON object. But, in your server side you're accepting application/x-www-form-urlencoded instead of application/json data. Which is causing this issue IMO.

Just replace the following code from

app.use(bodyParser.urlencoded({extended:true}));

to

app.use(bodyParser.json());

And give it a try once!

body-parser doc

Shashanth
  • 4,995
  • 7
  • 41
  • 51
  • I have one question, can you answer? I posted it in stack overflow but it shows the question is closed. – Gaurav Sharma Nov 11 '19 at 10:02
  • First search for the solutions and try it once. If you don't find any solution or if you're not able to solve it by yourself, ask a new question here on StackOverflow with proper [mcve]. If not me, other fellow SO users try to help you. Good luck! (if the question is too small you can ask it here I'll try to give you links to the answer) – Shashanth Nov 11 '19 at 10:07
  • I am working on a android app idea that needs to generate images on the basis of input entered by the user. Is there any library that can help? And can the image be generated on the phone itself, if yes then how? Or it can only be generated on server and then sent back to the client-side app.I found some answers that use html canvas to do this but I think this method is not preferable when the number of target user is huge because it will be slow, error-prone and will not be reliable. So how can I do keeping in mind factors like network speed, number of users, reliability? – Gaurav Sharma Nov 11 '19 at 10:10
  • What kind of images you want to generate? Like signature or what? – Shashanth Nov 11 '19 at 10:13
  • Like a receipt or bill or invoice etc. These types of images. – Gaurav Sharma Nov 11 '19 at 10:15
  • To be honest I never tried such type code. You need to prepare the format of the bill you want to print and set the data accordingly. To make it even simpler use external printers (bluetooth enabled printers). They provide sample code as well. But in that you can't generate image. And I saw your question it's on hold because for StackOveflow it's a too broad question to answer. – Shashanth Nov 11 '19 at 10:30