CURL リクエストを Ruby Gem HTTPClient に変換する方法
概要
この CURL リクエストを変換しようとしています。
curl \
-F 'slideshow_spec={
"images_urls": [
"<IMAGE_URL_1>",
"<IMAGE_URL_2>",
"<IMAGE_URL_3>"
],
"duration_ms": 2000,
"transition_ms": 200
}' \
-F 'access_token=<ACCESS_TOKEN>' \
https://google.com
HTTPClient リクエストに送信しましたが、すべての試行で 400 Bad Request が発生しました。私が試したことは次のとおりです。
payload = {
"images_urls": [
"https://cdn-m2.esoftsystems.com/10100028/TAASTRUP%40DANBOLIG.DK/10106239925/160596797/BEST_FIT/1542/1024/IMG_5511.jpg",
"https://cdn-m2.esoftsystems.com/10100028/TAASTRUP%40DANBOLIG.DK/10106239925/160596797/BEST_FIT/1542/1024/IMG_5511.jpg",
"https://cdn-m2.esoftsystems.com/10100028/TAASTRUP%40DANBOLIG.DK/10106239925/160596797/BEST_FIT/1542/1024/IMG_5511.jpg"
],
"duration_ms": 2000,
"transition_ms": 200
}
response = RestClient.post url, {slideshow_spec: payload.to_json, multipart: true, access_token: access_token}
何か案は?
解決策
あなたのリクエストは同等ではありません。ここでは JSON、Multipart、x-www-form-urlencoded 形式を混合していると思います。
RestClient は 3 つの形式すべてをサポートしています (例は https://github.com/rest-client/rest-client/blob/master/README.md から取得)
# POST JSON
RestClient.post "http://example.com/resource", {'x' => 1}.to_json, {content_type: :json, accept: :json}
# POST Multipart
# Usually not needed if you don't want to upload a file
RestClient.post '/data', {:foo => 'bar', :multipart => true}
# POST x-www-form-urlencoded
RestClient.post('https://httpbin.org/post', {foo: 'bar', baz: 'qux'})
あなたのcurlサンプルはapplication/x-www-form-urlencodedを使用しているのに対し、Rubyサンプルはmultipart/form-dataを使用しているようです。
背景情報については、以下を参照してください。