【问题标题】:Rails parameters are different when posting the same payload via Curl or Android通过 Curl 或 Android 发布相同的有效负载时,Rails 参数不同
【发布时间】:2017-07-24 18:01:33
【问题描述】:

从 Android 或通过 curling 发布相同的基本 JSON 时,结果会有所不同。

我想知道为什么?我假设 Rails 有一些我不理解的地方。

命令行 HTTP POST

curl 'http://localhost:3000/mobile/register' -X POST -H '内容类型: 应用程序/json' -d '{"user": {"email": "awesome@example.com", "password":"helloworld", "password_confirmation":"helloworld"}}'

服务器日志

参数:{"user"=>{"email"=>"awesome@example.com", “密码”=>“[过滤]”,“密码确认”=>“[过滤]”}, "注册"=>{"用户"=>{"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()...

服务器日志

参数: {"user"=>"{\"email\":\"awesome@example.com\",\"password\":\"helloworld\",\"password_confirmation\":\"helloworld\"}"}

铁路路线:

devise_scope :user do 
    namespace :mobile do
      post '/register', to: 'registrations#create', as: :register
    end
end


区别:

  • curling 会隐藏密码,但 Android 不会
  • curling 添加了一个额外的嵌套 JSON,所有数据都重复

我不确定是什么导致了这些差异?

更新

我在控制器操作中检查了request.env["CONTENT_TYPE"],发现Content-Type 存在差异。

卷曲 -> application/json

Android -> multipart/form-data; boundary=...

这会导致问题吗?

从Android端改过来容易吗?我在请求中添加了.header("Content-Type", "application/json"),但没有区别?

【问题讨论】:

    标签: android ruby-on-rails json curl


    【解决方案1】:

    我认为 Android HTTP POST 缺少 Content-Type: application/json 标头,因为它发送多部分表单数据。因此,rails 应用程序将其记录为纯字符串数据,而不是对其进行解析、注册用户和过滤密码。

    另外,在curl 命令的情况下,解析的 JSON 用户对象用于注册用户。重复的日志条目可能在此用户注册期间完成。

    要使两个请求等效,请尝试使用http://square.github.io/okhttp/ 中给出的POST TO A SERVER 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 2014-12-15
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多