Please ensure that your controller config accept POST method, may be it just receives GET.
And you can use RestClient (Plugin of Firefox or Chrome) to test your api.
문제
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 = "test@fromandroid.com";
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":"test@fromandroid.com","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!
올바른 솔루션이 없습니다
다른 팁
Please ensure that your controller config accept POST method, may be it just receives GET.
And you can use RestClient (Plugin of Firefox or Chrome) to test your api.
There are some issues you must have to follow to post
.
you need to post data something like:
{"user_params" : {"email":"test@fromandroid.com","name":"testName"}}
to create a user (according to your controller).
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.