乐闻世界logo
搜索文章和话题

How to send JSON requeto using ruby

1个答案

1

Sending JSON requests in Ruby typically requires using HTTP client libraries such as Net::HTTP, which is part of Ruby's standard library, or third-party gems like RestClient and HTTParty. The following provides detailed steps and examples for sending JSON requests using Net::HTTP.

Step 1: Add Required Libraries

First, ensure that the json library is installed in your environment and that you have required the net/http and uri libraries in your script.

Step 2: Set Up URI and HTTP Request

Create a URI object and initialize a Net::HTTP object to send the request.

Step 3: Create the Request Object

Based on the request type (GET, POST, PUT, DELETE, etc.), create the corresponding request object and set necessary headers, such as Content-Type.

Step 4: Add JSON Data to the Request Body

Convert your data to JSON format and add it to the request body.

Step 5: Send the Request and Handle the Response

Use the Net::HTTP object to send the request and retrieve the response. Process the response data according to your business logic.

Complete Example

ruby
require 'net/http' require 'json' require 'uri' uri = URI('http://example.com/api/resource') http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json') request.body = {name: 'John', email: 'john@example.com'}.to_json response = http.request(request) puts response.body

Important Notes

  • For HTTPS URLs, set http.use_ssl = true.
  • Handle exceptions and errors to ensure code robustness.
  • In production environments, sensitive information (such as API keys) should not be hardcoded directly in the code.

This example demonstrates how to send a POST request with JSON data using Ruby's standard library Net::HTTP. This method is flexible enough to be applied to various HTTP requests and handle different API requirements.

2024年6月29日 12:07 回复

你的答案