簡體   English   中英

將 POST 請求從 Rails 發送到本地 Web 服務時出現問題

[英]Issue with sending a POST request from Rails to Local Webservice

我正在嘗試向 Web 服務發送 POST 請求。 我使用的 curl 命令是:

curl --silent --header 'Accept: application/json' --header 'Content-Type: application/json' --data 
'{"mwtype":"serviceproviders/GetReport","url":"<an url>"}' http://localhost:8080/service/serviceproviders/v1

並且能夠成功給出響應。 在我的鐵路代碼中,我這樣做:

    uri = URI.parse("http://localhost:8080/service/serviceproviders/v1")
    res = Net::HTTP.post_form(uri, 'mwtype' => 'serviceproviders/GetReport', 'url' => '<some url>')
    if res.is_a?(Net::HTTPSuccess) 
      puts res.body
    else
      puts "Something went wrong"
      puts res
    end

但我收到了#<Net::HTTPBadRequest 400 Bad Request readbody=true> 我怎樣才能解決這個問題?

在您的 cURL 請求中,您發送的是 JSON。但Net::HTTP.post_form用於發送application/x-www-form-urlencoded表單數據對。

相反,您想使用普通post方法:

data = { 'mwtype' => 'serviceproviders/GetReport', 'url' => '<some url>' }
uri = URI.parse("http://localhost:8080/service/serviceproviders/v1")
res = Net::HTTP.post(uri, data.to_json, "Content-Type" => "application/json")

if res.is_a?(Net::HTTPSuccess) 
  puts res.body
else
  puts "Something went wrong"
  puts res
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM