How to send POST request from Android app to Rails application?

1.9k Views Asked by At

I have problem with sending POST request to my rails application from Android app (using Spring for Android)

I have following Rails controller:

  # POST /users
  # POST /users.json

  def create
@user = User.new(user_params)

respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render action: 'show', status: :created, location: @user }
  else
    format.html { render action: 'new' }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
  end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
  params.require(:user).permit(:name, :email)
end

I'm sending POST request (using Spring for Android):

        RestTemplate restTemplatePost = new RestTemplate();
        restTemplatePost.getMessageConverters().add(new StringHttpMessageConverter());


        UserDto user = new UserDto();
        user.name = "testName";
        user.email = "[email protected]";

        Gson gson = new Gson();
        String request = gson.toJson(user);
        restTemplatePost.postForObject(createUserUrl, request, String.class);
        } catch(RestClientException e) {
            Log.e("POST",e.getLocalizedMessage());
        }

value of String request is {"email":"[email protected]","name":"testName"}

and createUserUrl has value of: http://10.0.0.2:3000/users

however, I still get the following error:

> W/RestTemplate(3299): POST request for "http://10.0.0.2:3000/users"
> resulted in 400 (Bad Request); invoking error handler

I'm able to send the GET request, but POST doesn't work. What am I doing wrong? I used CURL to get better error message and it returns:

param not found: user 

so the problem might be with required user and optional name and emails parameters which are accepted by REST API, but how should I format user in json for it to work?

I'd greatly appreciate your help!

2

There are 2 best solutions below

0
On

Please ensure that your controller config accept POST method, may be it just receives GET.

RailsController

RailsRouting

And you can use RestClient (Plugin of Firefox or Chrome) to test your api.

Rest Client - Firefox

Rest Client - Chrome

1
On

There are some issues you must have to follow to post.

  1. you need to post data something like:

    {"user_params" : {"email":"[email protected]","name":"testName"}}

    to create a user (according to your controller).

  2. To post data add Request Header. As you sending json data, so header will be Content-Type: application/json.

Also I'm suggesting you to use a FireFox addons is named "RESTClient" to simulate this scenario.

Thanks.