请求将指定curl PUT命令转换为Ruby Net::HTTP代码示例
Converting Your curl PUT Request to Ruby Net::HTTP
I totally get it—most examples out there focus on POST requests, so figuring out PUT with all the headers and SSL skip can be tricky. Let's break down your curl command and translate it directly to Ruby's Net::HTTP step by step.
First, let's recap what your curl command is doing:
-k: Skips SSL certificate verification (insecure, but matches your original command)- Sets
AcceptandContent-Typeheaders to JSON - Uses PUT method with JSON payload
- Targets the specified HTTPS URL
Here's the corresponding Ruby code:
require 'net/http' require 'uri' require 'json' # Parse the target URL uri = URI('https://some.domain/repository/npm/-/user/org.couchdb.user:anonymous') # Create the HTTP connection object http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # Match curl's -k flag: disable SSL verification (NOT recommended for production!) http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Build the PUT request request = Net::HTTP::Put.new(uri) request['Accept'] = 'application/json' request['Content-Type'] = 'application/json' # Set the JSON payload request.body = JSON.generate({ name: 'anonymous', password: 'obfuscated' }) # Send the request and get the response response = http.request(request) # Optional: Handle the response (print status and body) puts "Response Status: #{response.code} #{response.message}" puts "Response Body: #{response.body}"
Key Notes:
- SSL Verification: The
verify_mode = VERIFY_NONEline replicates curl's-koption. This is unsafe for production environments—you should remove this line and ensure your server's SSL certificate is valid and trusted in production. - JSON Payload: We use
JSON.generateto convert the Ruby hash to a properly formatted JSON string, which matches the--datapart of your curl command. - Headers: We explicitly set the same
AcceptandContent-Typeheaders as your curl request to ensure the server handles the request correctly.
If you need to handle any edge cases (like timeouts, redirects, or additional authentication), feel free to ask for further adjustments—but this code should directly mirror the behavior of your original curl command.
内容的提问来源于stack exchange,提问作者mdo123
相关产品推荐
相关产品推荐

