使用HTTParty将Content-Type更改为JSON

Gra*_*Roy 14 ruby-on-rails salesforce httparty

我正在尝试使用Ruby on Rails与Salesforce API进行通信.我可以轻松地获取数据,但我在向服务器发布数据时遇到问题.我按照Quinton Wall的帖子使用HTTParty:

https://github.com/quintonwall/omniauth-rails3-forcedotcom/wiki/Build-Mobile-Apps-in-the-Cloud-with-Omniauth,-Httparty-and-Force.com

但我似乎能够从salesforce服务器获得的是我以html身份提交正文的错误

{"message"=>"此资源不支持'application/x-www-form-urlencoded'的MediaType","errorCode"=>"UNSUPPORTED_MEDIA_TYPE"}

负责的代码如下:

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
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么身体应该被发布为html以及如何改变这一点,以便它肯定像json一样,以便salesforce不拒绝它?

任何帮助,将不胜感激.干杯

小智 19

Content-Type标头需要设置为"application/json".这可以通过插入:headers => {'Content-Type'=>'application/json'}作为要发布的参数来完成,即:

response = post(Accounts.root_url+"/sobjects/Account/", 
  :body => {:name => "graham"}.to_json,
  :headers => {'Content-Type' => 'application/json'} )
Run Code Online (Sandbox Code Playgroud)


sup*_*ell 14

您必须将Content-Type标头设置为application/json.我没有使用过HTTParty,但看起来你必须做类似的事情

response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json) , :options => { :headers => { 'Content-Type' => 'application/json' } } )
Run Code Online (Sandbox Code Playgroud)

我有点惊讶格式选项不会自动执行此操作.