【发布时间】:2016-02-29 05:31:00
【问题描述】:
请帮助我理解,我做错了什么? 我需要从我的 Rails 应用程序向 api 发出 POST 请求,我首先尝试使用 gem“法拉第”,然后使用“net/http”。来自服务器的响应相同。帐户创建,但出现错误:
Net::HTTPBadResponse(错误的标题行格式)
class Connect
require 'uri'
require 'net/http'
require 'net/https'
require 'faraday'
def initialize(email, password, account)
@base_url = "https://example.com"
@client_id = ENV["client_id"]
@client_secret = ENV["client_secret"]
@email = email
@password = password
@account = account
end
# method with net/http
def create_account
@toSend = {
first_name: @account[:first_name],
last_name: @account[:last_name],
client_id: @client_id,
client_secret: @client_secret,
email: @email,
password: @password
}.to_json
uri = URI.parse("#{@base_url}/endclient/api/account")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(
uri.path,
initheader = {
'Content-Type' =>'application/json',
'Accept' =>'application/json'
}
)
req.body = "#{@toSend}"
res = https.request(req)
end
# faraday method
def make_account
conn = Faraday.new(:url => "#{@base_url}") do |faraday|
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
params = { first_name: @account[:first_name],
last_name: @account[:last_name],
client_id: @client_id,
client_secret: @client_secret,
email: @email,
password: @password
}.to_json
response = conn.post do |req|
req.url '/endclient/api/account'
req.headers['Content-Type'] = 'application/json'
req.headers['Accept'] = 'application/json'
req.body = params
end
end
end
通过Postman成功完成此请求,因此api的端点正在工作。
请帮助我了解标题有什么问题? 提前致谢!
更新:
这可能有问题吗?
Cannot render console with content type application/jsonAllowed content types: [#<Mime::Type:0x00000003661658 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x00000003660fc8 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x0000000365ca68 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]
【问题讨论】:
-
对于您的 net/http 方法,请尝试使用
req.body = @toSend.to_query而不是req.body = "#{@toSend}"。让我知道它是否有效。 -
@HarryBomrah,谢谢你的回答,我试过了,它给了我错误
ArgumentError (wrong number of arguments (0 for 1) -
哪一行?你有什么改变吗?
-
@HarryBomrah 在这行
req.body = @toSend.to_query,不,什么都不做。 -
从您的
@toSend = {...}.to_json中删除to_json
标签: ruby-on-rails net-http faraday