简体   繁体   中英

How to post json data with Rest API

require 'net/http'
require 'uri'
postData = Net::HTTP.post_form(URI.parse('http://localhost/restapi/index.php/api/posts'), 
                           {'id'=>9,'firstname'=>"test","lastname"=>"test"})
puts postData.body

How can I send data in JSON form?

@toSend = {"id" =>5,"firstname" => "anurag","lastname" => "arya"}

I also tried this but it did not work:

@toSend.to_json

Example:

require 'rubygems'
require 'net/http'
require 'uri'
require 'json'

url = "http://localhost/restapi/index.php/api/posts"
uri = URI.parse(url)
data = {"id"=>11,                                          
              "firstname"=>"PWD","lastname"=>"last"}     

headers = {'Content-Type' =>'application/json',               
                     'Accept-Encoding'=> "gzip,deflate",
                     'Accept' => "application/json"}

http = Net::HTTP.new(uri.host,uri.port)   # Creates a http object
#http.use_ssl = true                                          # When using https
#http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.post(uri.path,data.to_json,headers)
puts response.code
puts response.body
postData=Net::HTTP.post_form(URI.parse('http://localhost/oecprashant/yiiIndex.php/api/rubyREST'), 
                           {'data'=>jsonData})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM