programing

루비 전송 JSON 요청

golfzon 2023. 3. 25. 12:03
반응형

루비 전송 JSON 요청

루비로 JSON 요청을 보내려면 어떻게 해야 하나요?JSON 오브젝트가 있는데 그냥 할 수 있을 것 같지 않아요..sendjavascript로 폼을 보내야 하나요?

아니면 net/http 클래스를 루비로 사용할 수 있나요?

header - content type = json이고 body는 json 개체입니까?

uri = URI('https://myapp.com/api/v1/resource')
body = { param1: 'some value', param2: 'some other value' }
headers = { 'Content-Type': 'application/json' }
response = Net::HTTP.post(uri, body.to_json, headers)
require 'net/http'
require 'json'

def create_agent
    uri = URI('http://api.nsa.gov:1337/agent')
    http = Net::HTTP.new(uri.host, uri.port)
    req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
    req.body = {name: 'John Doe', role: 'agent'}.to_json
    res = http.request(req)
    puts "response #{res.body}"
rescue => e
    puts "failed #{e}"
end

HTTParty는 이것을 조금 더 쉽게 만들 수 있다고 생각합니다(또, 지금까지 본 다른 예에서는 동작하지 않았던 것 같은 nested json 등에서도 동작합니다.

require 'httparty'
HTTParty.post("http://localhost:3000/api/v1/users", body: {user: {email: 'user1@example.com', password: 'secret'}}).body

이것은 JSON 오브젝트와 응답 본문을 쓴 루비 2.4 HTTPS Post에서 작동합니다.

require 'net/http' #net/https does not have to be required anymore
require 'json'
require 'uri'

uri = URI('https://your.secure-url.com')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
  request.body = {parameter: 'value'}.to_json
  response = http.request request # Net::HTTPResponse object
  puts "response #{response.body}"
end

실제 예, NetHttps를 통해 Airbrake API에 새로운 도입을 통지합니다.

require 'uri'
require 'net/https'
require 'json'

class MakeHttpsRequest
  def call(url, hash_json)
    uri = URI.parse(url)
    req = Net::HTTP::Post.new(uri.to_s)
    req.body = hash_json.to_json
    req['Content-Type'] = 'application/json'
    # ... set more request headers 

    response = https(uri).request(req)

    response.body
  end

  private

  def https(uri)
    Net::HTTP.new(uri.host, uri.port).tap do |http|
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end

project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
  "environment":"production",
  "username":"tomas",
  "repository":"https://github.com/equivalent/scrapbook2",
  "revision":"live-20160905_0001",
  "version":"v2.0"
}

puts MakeHttpsRequest.new.call(url, body_hash)

주의:

Authorization header set header를 통해 인증을 수행하는 경우req['Authorization'] = "Token xxxxxxxxxxxx"또는 http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html 를 참조해 주세요.

Tom이 링크하고 있는 것보다 더 간단한 Json POST 요청 예를 참조하십시오.

require 'net/http'

uri = URI.parse("http://www.example.com/search.json")
response = Net::HTTP.post_form(uri, {"search" => "Berlin"})

저는 'unirest'라는 가벼운 http 요청 클라이언트를 좋아합니다.

gem install unirest

사용방법:

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => 23, :foo => "bar" }

response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body

2020년입니다.아무도 사용해서는 안 됩니다.Net::HTTP더 이상, 그리고 모든 대답이 그렇게 말하는 것처럼 보인다, 패러데이 - Github같은 높은 수준의 보석을 사용하라.


그렇긴 하지만, 제가 좋아하는 것은 HTTP API 호출에 대한 래퍼입니다.

rv = Transporter::FaradayHttp[url, options]

이를 통해 추가 의존관계 없이 HTTP 콜을 위조할 수 있기 때문입니다.

  if InfoSig.env?(:test) && !(url.to_s =~ /localhost/)
    response_body = FakerForTests[url: url, options: options]

  else
    conn = Faraday::Connection.new url, connection_options

가짜가 이렇게 생겼을

HTTP의 모킹/스터빙 프레임워크가 있다는 것은 알고 있습니다만, 적어도 지난번 조사했을 때는 요구를 효율적으로 검증할 수 없었고, 예를 들어 원시 TCP 교환이 아닌 HTTP만을 위한 것이었기 때문에 이 시스템은 모든 API 통신을 위한 통합 프레임워크를 가질 수 있습니다.


해시를 json으로 빠르게 더티하게 변환하고 싶다면, API를 테스트하고 응답을 루비로 해석하기 위해 json을 리모트호스트에 송신하는 것이 추가 보석을 사용하지 않는 가장 빠른 방법일 것입니다.

JSON.load `curl -H 'Content-Type:application/json' -H 'Accept:application/json' -X POST localhost:3000/simple_api -d '#{message.to_json}'`

말할 필요도 없지만, 이것을 실전 가동에 사용하지 말아 주세요.

net/http api는 사용하기 어려울 수 있습니다.

require "net/http"

uri = URI.parse(uri)

Net::HTTP.new(uri.host, uri.port).start do |client|
  request                 = Net::HTTP::Post.new(uri.path)
  request.body            = "{}"
  request["Content-Type"] = "application/json"
  client.request(request)
end
data = {a: {b: [1, 2]}}.to_json
uri = URI 'https://myapp.com/api/v1/resource'
https = Net::HTTP.new uri.host, uri.port
https.use_ssl = true
https.post2 uri.path, data, 'Content-Type' => 'application/json'

언급URL : https://stackoverflow.com/questions/2024805/ruby-send-json-request

반응형