簡體   English   中英

如何使用Rest API發布JSON數據

[英]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

如何以JSON格式發送數據?

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

我也試過了,但是沒有用:

@toSend.to_json

例:

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})

暫無
暫無

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

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