5
10

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.

Faradayの使い方

Posted at

FaradayというHTTPクライアントライブラリがとても良い
後で見返すためにメモ

##Faradayの使い方
Gemfileはこんな感じ

Gemfile
  # httpリクエスト
  gem 'faraday'
  # リダイレクトを追う
  gem 'faraday_middleware'
  # クッキーを扱う
  gem 'faraday-cookie_jar'

ファイルのアップロードとかする時はmultipartを指定するのかな?
間違ってたらごめんなさい

hoge.rb
    conn = Faraday.new(:url => 'https://www.hoge.com/') do |faraday|
      faraday.request :multipart
      faraday.request  :url_encoded
      faraday.adapter :net_http
    end

簡単にgetリクエストが出来る

hoge.rb
    conn.get do |req|
      req.url '/foge'
    end

postしたい場合はPOSTを指定すれば簡単に出来る
下記はcookieを指定して、画像をアップロードする例

hoge.rb
    conn.post do |req|
      req.url '/foge'
      req.headers['Cookie'] = cookie
      req.headers['Content-Type'] = 'image'
      req.body = {
        name: "hoge",
        image: Faraday::UploadIO.new('hoge.jpg', 'image/jpeg')
      }
    end

キーを付けないでPOST出来ました
下記はaudioを送信する例

hoge.rb
    conn.post do |req|
      req.url '/foge'
      req.headers['Cookie'] = cookie
      req.headers['Content-Type'] = 'audio/l16; rate=16000;'
      req.body = File.binread("hoge.wav")
    end
5
10
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
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?