Rails parameters are different when posting the same payload via Curl or Android
When posting the same basic JSON from Android or via curling, the result is different.
I'm trying to understand why? I'm assuming there is something about Rails that I don't understand.
Command Line HTTP POST
curl 'http://localhost:3000/mobile/register' -X POST -H 'Content-Type: application/json' -d '{"user": {"email": "awesome@example.com", "password":"helloworld", "password_confirmation":"helloworld"}}'
Server logs
Parameters: {"user"=>{"email"=>"awesome@example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "registration"=>{"user"=>{"email"=>"awesome@example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}}
Android HTTP POST
OkHttpClient client = new OkHttpClient();
JSONObject userObject = new JSONObject();
userObject.put("email", mUserEmail);
userObject.put("password", mUserPassword);
userObject.put("password_confirmation", mUserPasswordConfirmation);
String userString = userObject.toString();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("user", userString)
.build();
Request request = new Request.Builder()
.url(REGISTER_API_ENDPOINT_URL)
.method("POST", RequestBody.create(null, new byte[0]))
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback()...
Server logs
Parameters: {"user"=>"{"email":"awesome@example.com","password":"helloworld","password_confirmation":"helloworld"}"}
Rails Routes:
devise_scope :user do
namespace :mobile do
post '/register', to: 'registrations#create', as: :register
end
end
Differences:
I'm not sure what causes these differences?
UPDATE
I checked request.env["CONTENT_TYPE"]
in the controller action and I am seeing differences in Content-Type
.
Curl -> application/json
Android -> multipart/form-data; boundary=...
multipart/form-data; boundary=...
Could this cause the issue?
Is it easy to change from the Android side? I added .header("Content-Type", "application/json")
to the request but it makes no difference?
I think the Android HTTP POST lacks the Content-Type: application/json
header because it sends multipart form data . So the rails app logs it as plain string data instead of parsing it, registering user and filtering password.
Also, in case of curl
command, the parsed JSON user object is used to register a user. The repeated log entry is perhaps done during this user registration.
To make both requests equivalent, try using the POST TO A SERVER
example given at http://square.github.io/okhttp/.
上一篇: HTTP POST请求发送图像