Ruby 关于腾讯 API 拼 URL 的服务

davidzhu001 · December 15, 2018 · Last by aoner replied at December 20, 2018 · 2234 hits

##问题前先问候 腾讯 api 的请求格式 要求 key=value 拼在 url 的后面例如

&SecretId=xxxxxxx
&Region=ap-guangzhou
&Timestamp=1402992826
&Nonce=345122
&Signature=xxxxxxxx
&Version=2017-03-12

我经常使用的是 rest-client

#get
RestClient.get('https://httpbin.org/get', params: {foo: 'bar', baz: 'qux'})
# GET "https://httpbin.org/get?foo=bar&baz=qux"

#post
>> r = RestClient.post('https://httpbin.org/post', {foo: 'bar', baz: 'qux'})
# POST "https://httpbin.org/post", data: "foo=bar&baz=qux"

当我拼自己的 url 的时候 get 都能通过。 Post 的话,会将请求失败。查看了原因 post 大多数会把 url 后面的 key=val 变成了参数。 尝试了下 ruby 流行的库貌似 post 都不能变成 key=val 的形式。

所以请求一个答案!

并表示对腾讯的这种方式很不理解,如果有好心人也能指教下。腾讯的方法为什么那么独特。

表示腾讯是文档做得最垃圾的一家。。。

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            timeout: 10, headers: {params: {foo: 'bar'}})
# ➔ GET http://example.com/resource?foo=bar

当年也是因为要用腾讯的 API 才知道 RestClient 还可以这么用的

看了下 Rest Client 的 API,后面还是作为 Hash 参数传进去的,只是因为 Post 前面多了个参数,所以被传错地方了。于是多传一个 nil 进去就好了。

require 'rest-client'
require 'json'

r = RestClient.post('https://httpbin.org/post', nil, params: {foo: 'bar', baz: 'qux'})
JSON.parse(r.body)
# => {"args"=>{"baz"=>"qux", "foo"=>"bar"}, "data"=>"", "files"=>{}, "form"=>{}, "headers"=>{"Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate", "Connection"=>"close", "Content-Length"=>"0", "Content-Type"=>"application/x-www-form-urlencoded", "Host"=>"httpbin.org", "User-Agent"=>"rest-client/2.0.2 (darwin18.0.0 x86_64) ruby/2.5.3p105"}, "json"=>nil, "origin"=>"0.0.0.0", "url"=>"https://httpbin.org/post?foo=bar&baz=qux"}

@dsh0416 @coderliu 还是不行 @coderliu 我想找下 post 的方法

params =  { foo: 'bar', baz: 'qux' }
uri = URI('https://httpbin.org/post')
uri.query = params.to_query
url = uri.to_s
RestClient.post url, {}
Reply to davidzhu001

那你要说是那个 API 了,不知道具体需求

没试,纯猜

RestClient.post('http://example.com/resource',
                          {foo: 'bar'},
                          {content_type: "application/application/x-www-form-urlencoded"})
You need to Sign in before reply, if you don't have an account, please Sign up first.