【问题标题】:HTTParty POST call returning invalid JSONHTTParty POST 调用返回无效的 JSON
【发布时间】:2019-12-11 12:20:03
【问题描述】:

我希望使用我的电子邮件地址向 API 发帖,但我无法获得可行的回复。当我在终端中简单地卷曲 API 时,数据按预期返回。

@omnics2 = HTTParty.post('https://qo.api.liveramp.com/v1/idl_resolution',
:headers => {
      'Content-Type' => 'application/json',
      'Accept' => 'application/json',
      'X-Api-Key' => 'my api key', 
      'Accept-Encoding' => 'gzip, deflate',             
      'Content-Length' => '59148' 
             },
  :body => {'email' => 'me@email.com'}
      )

上面返回这个错误

<HTTParty::Response:0x7ff5b0d49ab0 parsed_response="Invalid JSON in request: invalid character 'e' looking for beginning of value\n", @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"content-type"=>["text/plain; charset=utf-8"], "x-content-type-options"=>["nosniff"], "date"=>["Fri, 02 Aug 2019 21:41:58 GMT"], "content-length"=>["78"], "via"=>["1.1 google"], "alt-svc"=>["clear"], "connection"=>["close"]}>

我可以用.to_json 方法包装整个调用,这样可以成功调用,但我无法使用标准@omnics.body 方法对响应做任何事情。当我将所有内容包装在 .to_json 方法中时,我得到的结果是:

 => "{\"content-type\":[\"text/plain; charset=utf-8\"],\"x-content-type-options\":[\"nosniff\"],\"date\":[\"Fri, 02 Aug 2019 21:45:32 GMT\"],\"content-length\":[\"78\"],\"via\":[\"1.1 google\"],\"alt-svc\":[\"clear\"],\"connection\":[\"close\"]}"

我尝试将 to_json 方法添加到标题部分和正文部分,推荐 here 如下所示: :body =&gt; {'email' =&gt; 'me@email.com'}.to_json 而不是包装整个函数,但这也会出错。

我会喜欢这里的任何想法,因为我只是一个最业余的开发人员,并且可能忽略了一些显而易见的事情。

【问题讨论】:

  • 进步! @omnics3 = HTTParty.post("https://qo.api.liveramp.com/v1/idl_resolution", options) options = { headers: { "Content-Type": "application/json", "X-Api-Key" =&gt; "key" }, query: { data: true }, body: { email: ["value"] }.to_json } 这超出了 JSON 错误的范围,但看起来 api 需要将对象(即email_sha1)嵌套在“[”对象中。没有它,我会收到以下错误:json: cannot unmarshal object into Go value of type []quickonboarding.QORecord 如此处所示quick-onboard.readme.io/reference

标签: ruby-on-rails json httparty


【解决方案1】:

终于搞定了。我必须将主体值包含在一个数组中。语法如下:

@omnics3 = HTTParty.post("https://qo.api.liveramp.com/v1/idl_resolution", options)

    options = {
      headers: {
        "Content-Type": "application/json",
        "X-Api-Key" => "my api key"
      },
      :debug_output => STDOUT,
      query: { data: true },
      body: [
        { email: ["anemail@address.com"]  },
        { email: ["joe@gmail.com"] },

    ].to_json
    }

【讨论】:

    猜你喜欢
    • 2013-12-20
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多