1
0

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.

ItayaAdvent Calendar 2022

Day 20

Ruby+MechanizeでjsonデータをPOSTする方法

Posted at

概要

Ruby+MechanizeでPOSTリクエストをしようと思ったのですが、調べてみるとフォームを選択して...ってやり方がたくさん出てきたので、そうではなく純粋なpostリクエストをする方法を紹介する

だめだった例

パターン1

自分がやってみて行けそうだったけどだめだった書き方

require 'mechanize'

agent = Mechanize.new
payload = {
  text: 'こんにちわ'
}
page = agent.post('https://xxx.yyyy.zzz', payload)

一見POSTできそうなのですが、

/var/task/vendor/bundle/ruby/2.7.0/gems/mechanize-2.8.5/lib/mechanize/http/agent.rb:333:in `fetch': 400 => Net::HTTPBadRequest for https://xxx.yyyy.zzz -- unhandled response (Mechanize::ResponseCodeError)

これではだめでした...

パターン2

次に試したのがpayloadのデータをto_jsonする方法

require 'mechanize'
require 'json'

agent = Mechanize.new
payload = {
  text: 'こんにちわ'
}
page = agent.post('https://xxx.yyyy.zzz', payload.to_json)

これも同様のエラーが出てだめでした

/var/task/vendor/bundle/ruby/2.7.0/gems/mechanize-2.8.5/lib/mechanize/http/agent.rb:333:in `fetch': 400 => Net::HTTPBadRequest for https://xxx.yyyy.zzz -- unhandled response (Mechanize::ResponseCodeError)

うまくいったコード

require 'mechanize'
require 'json'

agent = Mechanize.new
payload = {
  text: 'こんにちわ'
}
page = agent.post('https://xxx.yyyy.zzz', payload.to_json, {'Content-Type' => 'application/json'})

失敗2にプラスしてContent-Typeを指定しました。

これで問題なくPOSTできました!!

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?