30
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Net::HTTPのコードを簡潔に書いてみた

Last updated at Posted at 2014-11-25

RubyのNET::HTTPを使ったコードが汚い!!
リファクタリングしたい!!
ってなったので、よく使う部分を以下に。

コード

require 'net/http'

uri = URI.parse 'http://example.com'

params = Hash.new
params.store("hoge","1")
params.store("fuga","2")

if method == :get
  uri.query = URI.encode_www_form(params)
  req = Net::HTTP::Get.new uri
end

if method == :post
  req = Net::HTTP::Post.new uri.path
  req.set_form_data(params)
end

res = Net::HTTP.start(uri.host, uri.port) {|http| http.request req }

参考

Get

Class: Net::HTTP (Ruby 2.1.5)
module URI

Post

Net::HTTP Cheat Sheet

おまけ

って記事を書いたあとに友人から教えてもらいました。
Net::HTTPを無理に使う必要のない方は以下を使ったほうが幸せになれるかも。
rest-client/rest-client

30
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?