代码之家  ›  专栏  ›  技术社区  ›  Ryan Florence

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

  •  12
  • Ryan Florence  · 技术社区  · 17 年前

    在PHP中,我可以这样做:

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

    我如何在Ruby中做同样的事情(或者一些Rails方法?)

    我在谷歌上搜索了半个小时,结果完全不见了。

    4 回复  |  直到 15 年前
        1
  •  19
  •   glenn jackman    17 年前

    标准库包 open-uri 你所追求的是:

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

    不知道为什么我之前没有找到这个。除非有更好的方法,否则我就这么做!

        3
  •  0
  •   Mike Buckbee    17 年前

    在你看来,试试看

    <%= request.inspect %>
    
        4
  •  0
  •   Mullins    15 年前

    使用net/http库,如图所示:

    require 'net/http'
    
    response = Net::HTTP.get_response('mysite.com','/api/v1/messages')
    p response.body
    
    推荐文章