这是我想要执行的卷曲请求:
curl --request GET --url 'https://us8.api.mailchimp.com/3.0/' --user 'anystring:<apikey>'
从命令行运行这个curl命令,我得到了一堆JSON,这就是我想要的。
我尝试使用Faraday执行相同的请求。这就是我尝试过的:
conn = Faraday.new "https://us8.api.mailchimp.com/3.0/" do |faraday|
faraday.adapter Faraday.default_adapter
end
conn.basic_auth('apikey', <apikey>)
response = conn.get
puts response.body # => "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head>...
如何获取JSON而不是我在response.body
中看到的html?
答案 0 :(得分:2)
这最终为我工作:
conn = Faraday.new('https://us8.api.mailchimp.com/3.0/') do |c|
c.use FaradayMiddleware::ParseJson, content_type: "application/json"
c.use Faraday::Adapter::NetHttp
end
conn.basic_auth('apikey', <api_key>)
response = conn.get('campaigns')
puts response # => json blob
答案 1 :(得分:0)
这是使用ruby gem进行卷曲操作的farday代码。
def contacts
response = JSON.parse(params)
@conn = Faraday.new('https://domain.example.com/api/v2/') do |farday|
farday.use FaradayMiddleware::ParseJson, content_type: "application/json"
farday.use Faraday::Adapter::NetHttp
end
@conn.basic_auth('apikey', <your_api_key>)
response = @conn.get('contacts')
puts response
render :json => {"success" => true}
end
答案 2 :(得分:0)
一个更为简洁的选择是将您的凭据手动编码为Base64并手动设置Authorization
标头。这样可以节省几行代码,并使其与常规的法拉第请求(即Faraday.post <URL>, <BODY>, <HEADERS>
)保持类似的格式。
即
encoded_credentials = Base64.encode64('apikey:api_secret').chomp
Faraday.post 'http://myhost.local/my_url', {}, authorization: "Basic #{encoded_credentials}"