Ruby-on-rails 使用 HTTParty 将 Content-Type 更改为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6154176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing Content-Type to JSON using HTTParty
提问by GrahamJRoy
I am trying to use Ruby on Rails to communicate with the Salesforce API. I can fetch data easily enough but I am having problems posting data to the server. I am using HTTParty as per Quinton Wall's post here:
我正在尝试使用 Ruby on Rails 与 Salesforce API 进行通信。我可以很容易地获取数据,但是我在将数据发布到服务器时遇到了问题。根据 Quinton Wall 的帖子,我正在使用 HTTParty:
but all I seem to be able to get from the salesforce server is the error that I am submitting the body as html
但我似乎能够从 salesforce 服务器得到的只是我将正文作为 html 提交的错误
{"message"=>"MediaType of 'application/x-www-form-urlencoded' is not supported by this resource", "errorCode"=>"UNSUPPORTED_MEDIA_TYPE"}
{"message"=>"此资源不支持'application/x-www-form-urlencoded'的媒体类型", "errorCode"=>"UNSUPPORTED_MEDIA_TYPE"}
the responsible code looks like:
负责的代码如下所示:
require 'rubygems'
require 'httparty'
class Accounts
include HTTParty
format :json
...[set headers and root_url etc]
def self.save
Accounts.set_headers
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json))
end
end
anyone have an idea why the body should be being posted as html and how to change this so that it definitely goes as json so that salesforce doesn't reject it?
任何人都知道为什么正文应该作为 html 发布以及如何更改它,以便它绝对作为 json 进行发布,以便 salesforce 不会拒绝它?
Any help would be appreciated. cheers
任何帮助,将不胜感激。干杯
采纳答案by superfell
You have to set the Content-Type header to application/json. I haven't used HTTParty, but it looks like you have to do something like
您必须将 Content-Type 标头设置为 application/json。我没有使用过 HTTParty,但看起来你必须做一些类似的事情
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json) , :options => { :headers => { 'Content-Type' => 'application/json' } } )
I'm somewhat surpised that the format option doesn't do this automatically.
我有点惊讶格式选项不会自动执行此操作。
回答by jesse
The Content-Type header needs to be set to "application/json". This can be done by inserting :headers => {'Content-Type' => 'application/json'}as a parameter to post, ie:
Content-Type 标头需要设置为“application/json”。这可以通过插入:headers => {'Content-Type' => 'application/json'}作为post的参数来完成,即:
response = post(Accounts.root_url+"/sobjects/Account/",
:body => {:name => "graham"}.to_json,
:headers => {'Content-Type' => 'application/json'} )

