0
1

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 1 year has passed since last update.

Ruby の http クライアントの使い方 (Post)

Last updated at Posted at 2018-11-22

faraday というライブラリーを使います。

プログラム

http_post.rb
#! /usr/bin/ruby
# -*- encoding: utf-8 -*-
#
#	http_post.rb
#
#					Nov/22/2018
#
# ---------------------------------------------------------------------
require 'faraday'
require 'json'
#
# ---------------------------------------------------------------------
STDERR.puts	"*** 開始 ***"
#
URL="https://httpbin.org/post"
#
args = {}
args['user'] = 'jiro'
args['password'] = '123456'
#res = Faraday.post URL
con = Faraday.new 
res = con.post do |req|
	req.url URL
	req.headers['Content-Type'] = 'application/json'
	req.body = JSON.pretty_generate(args)
end

# puts	res
puts	res.status
# puts	res.body

json_str = res.body

dict_data=JSON.parse(json_str)
#
puts	"Host:\t" + dict_data['headers']['Host']
puts	"origin:\t" + dict_data['origin']
puts	"url:\t" + dict_data['url']
#
STDERR.puts	"*** 終了 ***"
# ---------------------------------------------------------------------

実行結果

$ ./http_post.rb 
Top level ::CompositeIO is deprecated, require 'multipart/post' and use `Multipart::Post::CompositeReadIO` instead!
Top level ::Parts is deprecated, require 'multipart/post' and use `Multipart::Post::Parts` instead!
*** 開始 ***
200
Host:	httpbin.org
origin:	219.126.135.100
url:	https://httpbin.org/post
*** 終了 ***

確認したバージョン

$ ruby --version
ruby 3.0.5p211 (2022-11-24 revision ba5cf0f7c5) [x86_64-linux]

$ pacman -Q ruby-faraday
ruby-faraday 1.8.0-1
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?