简体   繁体   English

如何在Ruby中获取http请求的内容?

[英]How do I get the contents of an http request in Ruby?

In PHP I can do this: 在PHP中我可以这样做:

$request = "http://www.example.com/someData";
$response = file_get_contents($request);

How would I do the same thing in Ruby (or some Rails method?) 我如何在Ruby(或一些Rails方法?)中做同样的事情?

I've been googling for a half an hour and coming up completely short. 我一直在谷歌搜索半小时,然后完全缩短。

The standard library package open-uri is what you're after: 标准库包open-uri就是您所追求的:

require 'open-uri'
contents = open('http://www.example.com') {|io| io.read}
# or
contents = URI.parse('http://www.example.com').read
require 'net/http'
Net::HTTP.get(URI.parse('http://www.example.com/index.html'))

Not sure why I didn't find this earlier. 不知道为什么我之前没有找到这个。 Unless there's an better way, I'm going with this! 除非有更好的方法,否则我会选择这个!

在你看来尝试

<%= request.inspect %>

Using the net/http library as shown: 使用net / http库如图所示:

require 'net/http'

response = Net::HTTP.get_response('mysite.com','/api/v1/messages')
p response.body

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM