python 中的 urllib2 相当于 ruby [英] urllib2 in python equivalent for ruby
问题描述
我在 python 中有一些代码可以在 python 中发送一个 http 请求,但我试图弄清楚如何在 ruby 中执行它,因为我的服务器是 rails.
I have some code in python that sends an http request in python, but I am trying to figure out how to do it in ruby since my server is rails.
import urllib2, sys, json
url = "http://new.openbms.org/backend/api/query"
query = "select *"
fp = urllib2.urlopen(url, data=query)
obj = json.load(fp)
json.dump(obj, sys.stdout, sort_keys=True, indent=2)
这个 python 代码实际上确实返回了我所期望的,但是当我在 ruby 中尝试同样的事情时,我得到了一个错误的请求
This python code actually does return what I expect, but when I try to same thing in ruby I get a bad request
require 'net/http'
query = "select *"
url = "http://new.openbms.org/backend/api/query"
uri = URI(url)
p Net::HTTP.post_form(uri, { "data" => query })
上面的这个打印输出 #
.请帮忙,谢谢.
This one above print outs #<Net::HTTPBadRequest 400 Bad Request readbody=true>
. Please help, thanks.
Python 版本 2.7.1Ruby 版本 1.9.2p318
Python version 2.7.1 Ruby version 1.9.2p318
推荐答案
虽然你调用远程服务器就好像它响应 application/x-www-form-urlencoded 数据一样,实际上它只是响应一个命令帖子正文.
Although you're calling the remote server as if it responds to application/x-www-form-urlencoded data, in fact it's just responding to a command in the post body.
在 Python 中,urllib2.urlopen 的数据参数需要一个字符串,它是 application/x-www-form-urlencoded
.
In Python, urllib2.urlopen's data parameter expects a string that's application/x-www-form-urlencoded
.
select *
不是真正的形式编码可以这么说,但无论如何它对你有用,因为服务器将它解释为名为 select *
的查询参数None
值,或者更准确地说,服务器看到带有 select *
的帖子正文并说我知道如何响应该命令".
select *
isn't really form encoded so to speak, but it's working for you anyway because the server is interpreting it as a query argument named select *
with a None
value, or more precisely, the server sees a post body with select *
and says "I know how to respond to that command".
因此,这里有一个与您正在做的事情等效的 Ruby.
So, a Ruby equivalent to what you're doing is here.
require 'net/http'
require 'json'
query = "select *"
url = "http://new.openbms.org/backend/api/query"
uri = URI(url)
response = Net::HTTP.post_form(uri, { query => nil })
puts JSON.parse(response.body)
这篇关于python 中的 urllib2 相当于 ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!