Chuyển đổi lệnh curl thành mã Ruby - Tạo mã Ruby Net::HTTP sẵn sàng sử dụng cho các yêu cầu API
# Ruby Net::HTTP code will appear here # Example: require 'net/http' require 'uri' require 'json' uri = URI.parse('https://api.example.com/data') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' request = Net::HTTP::Post.new(uri.path) request['Content-Type'] = 'application/json' request.body = JSON.dump({name: 'test'}) response = http.request(request) puts response.code puts response.body
Dưới đây là một số lệnh curl phổ biến mà bạn có thể chuyển đổi thành mã Ruby:
curl https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"[email protected]"}' https://api.example.com/users
curl -X PUT -H "Authorization: Bearer token123" -d '{"status":"active"}' https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
curl -H "X-API-Key: abc123" -H "Accept: application/json" https://api.example.com/data
Thư viện Net::HTTP của Ruby là một cách mạnh mẽ để thực hiện các yêu cầu HTTP. Dưới đây là một số mẫu Ruby Net::HTTP phổ biến:
require 'net/http' require 'uri' uri = URI.parse('https://api.example.com/upload') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' request = Net::HTTP::Post.new(uri.path) request['Authorization'] = 'Bearer YOUR_TOKEN_HERE' # Create multipart form data boundary = "AaB03x" post_body = [] post_body << "--#{boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"file\"; filename=\"document.pdf\"\r\n" post_body << "Content-Type: application/pdf\r\n\r\n" post_body << File.read('document.pdf') post_body << "\r\n--#{boundary}--\r\n" request['Content-Type'] = "multipart/form-data; boundary=#{boundary}" request.body = post_body.join response = http.request(request) puts response.body
require 'net/http' require 'uri' require 'json' uri = URI.parse('https://api.example.com/data') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == 'https' http.open_timeout = 5 # seconds http.read_timeout = 5 # seconds begin request = Net::HTTP::Get.new(uri.request_uri) response = http.request(request) case response when Net::HTTPSuccess data = JSON.parse(response.body) puts data else puts "Error: #{response.code} - #{response.message}" end rescue Net::OpenTimeout puts "Connection timed out" rescue Net::ReadTimeout puts "Response timed out" rescue StandardError => e puts "Error making request: #{e.message}" end
Sao chép lệnh curl của bạn → Dán vào hộp nhập liệu → Nhận mã Ruby Net::HTTP đã chuyển đổi
Bộ chuyển đổi của chúng tôi hỗ trợ các lệnh curl phức tạp và chuyển đổi chúng thành mã Ruby sạch, hiệu quả sử dụng thư viện Net::HTTP
Công cụ của chúng tôi xử lý các tùy chọn curl phổ biến này và chuyển đổi chúng thành mã Ruby Net::HTTP thích hợp:
Đ: Mã Ruby Net::HTTP được tạo tương thích với Ruby 2.0 trở lên. Đối với các phiên bản Ruby cũ hơn, có thể cần điều chỉnh nhỏ.
Đ: Mã cơ bản được tạo không bao gồm xử lý lỗi mở rộng. Đối với mã sản xuất, bạn nên thêm các khối begin/rescue để xử lý các ngoại lệ tiềm ẩn như Net::HTTPError hoặc vấn đề kết nối.
Đ: Đối với phản hồi JSON, sử dụng JSON.parse(response.body) để phân tích phản hồi thành một hash Ruby. Đối với các định dạng khác, bạn có thể sử dụng response.body cho nội dung thô.
Đ: Thư viện Net::HTTP là một phần của thư viện chuẩn Ruby, vì vậy không cần gem bổ sung cho các yêu cầu HTTP cơ bản. Đối với xử lý JSON, gem 'json' được bao gồm trong thư viện chuẩn kể từ Ruby 1.9.
Đ: Đối với tải lên tệp trong Ruby, bạn cần sử dụng dữ liệu biểu mẫu đa phần với Net::HTTP. Bộ chuyển đổi của chúng tôi xử lý các lệnh curl với tùy chọn -F
hoặc --form
và tạo mã Ruby thích hợp.
Đ: Thư viện Net::HTTP của Ruby cung cấp xử lý cookie thông qua HTTP::Cookie jar. Khi bạn chuyển đổi các lệnh curl bao gồm xử lý cookie (sử dụng -b
hoặc --cookie
), công cụ của chúng tôi tạo mã Ruby quản lý cookie đúng cách.
Đ: Trong khi curl rất tốt cho kiểm thử API dòng lệnh nhanh, Ruby Net::HTTP cung cấp một cách tiếp cận lập trình tích hợp với ứng dụng Ruby của bạn. Chuyển đổi curl sang Ruby giúp bắc cầu khoảng cách giữa kiểm thử và triển khai trong phát triển Ruby.
Hiểu các lệnh curl là điều cần thiết cho kiểm thử API hiệu quả với Ruby. Dưới đây là tham khảo nhanh về các tùy chọn curl phổ biến mà bộ chuyển đổi của chúng tôi hỗ trợ:
curl [options] [URL]
-X, --request METHOD
: Specify request method (GET, POST, PUT, DELETE, etc.)-H, --header LINE
: Add header to the request-d, --data DATA
: Send data in POST request-F, --form CONTENT
: Submit form data-u, --user USER:PASSWORD
: Server user and password-k, --insecure
: Allow insecure server connections-I, --head
: Show document info only-v, --verbose
: Make the operation more verbose-s, --silent
: Silent mode--connect-timeout SECONDS
: Maximum time for connectionBộ chuyển đổi Ruby của chúng tôi xử lý các lệnh curl phức tạp bao gồm nhiều header, xác thực, tải trọng dữ liệu và các tùy chọn khác nhau. Chỉ cần dán lệnh curl của bạn và nhận mã Ruby sạch, hiện đại sử dụng thư viện Net::HTTP.
Khi làm việc với thư viện Ruby Net::HTTP, hãy tuân theo các thực hành tốt nhất sau đây để tương tác API hiệu quả và an toàn:
require 'net/http' require 'uri' uri = URI.parse('https://api.example.com') Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| # First request request1 = Net::HTTP::Get.new('/users') response1 = http.request(request1) # Second request (uses same connection) request2 = Net::HTTP::Get.new('/products') response2 = http.request(request2) end
require 'net/http' require 'uri' uri = URI.parse('https://api.example.com/data') begin response = Net::HTTP.get_response(uri) case response when Net::HTTPSuccess puts "Success: #{response.body}" when Net::HTTPRedirection puts "Redirection to: #{response['location']}" when Net::HTTPClientError puts "Client error: #{response.code} - #{response.message}" when Net::HTTPServerError puts "Server error: #{response.code} - #{response.message}" else puts "Unknown response: #{response.code} - #{response.message}" end rescue SocketError => e puts "Connection error: #{e.message}" rescue Timeout::Error puts "Connection timed out" rescue StandardError => e puts "Error: #{e.message}" end
require 'net/http' require 'uri' require 'json' uri = URI.parse('https://api.example.com/data') response = Net::HTTP.get_response(uri) begin data = JSON.parse(response.body) puts data['name'] rescue JSON::ParserError => e puts "Invalid JSON response: #{e.message}" end