Connecting to web services using Rails (HTTP requests)?

前端 未结 6 1733
终归单人心
终归单人心 2021-02-06 10:45

I am using Ruby on Rails 3 and I am trying to implement APIs to retrieve account information from a web service. That is, I would like to connect to a web service that has the A

6条回答
  •  攒了一身酷
    2021-02-06 11:09

    If you don't need low-level tweak-ability offered by Net::HTTP, instead take a look at using Open-URI, which comes with Ruby. It makes it easy to request a page and receive the body back. Open-URI doesn't have all the bells and whistles but for a lot of what I do it's plenty good.

    A simple use looks like:

    require 'open-uri'
    body = open('http://www.example.com').read
    

    The docs have many other examples.

    These are other HTTP clients I like:

    • HTTPClient
    • Typhoeus

    They are more tweakable and can handle multiple connections at once if that's what you need. For instance, Typhoeus has a suite of simplified calls, similar to Open-URI's. From the docs:

    response = Typhoeus::Request.get("http://www.pauldix.net")
    response = Typhoeus::Request.head("http://www.pauldix.net")
    response = Typhoeus::Request.put("http://localhost:3000/posts/1", :body => "whoo, a body")
    response = Typhoeus::Request.post("http://localhost:3000/posts", :params => {:title => "test post", :content => "this is my test"})
    response = Typhoeus::Request.delete("http://localhost:3000/posts/1")
    

    HTTPClient has similar shortened methods too.

提交回复
热议问题