You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Ruby HTTPClient设置JSON类型的Content-Type?

Fixing HTTPClient JSON Content-Type & JSONClient NameError Issues

Hey there! Let's work through your HTTPClient problems one by one:

1. Setting JSON Content-Type with HTTPClient

You don't need to hunt for a separate "headers hash"—HTTPClient lets you specify headers directly in your request calls, or set them globally as defaults. Here's how to do both:

Option 1: Set headers per request

When sending JSON data, first serialize your hash to a JSON string, then pass the Content-Type header in the request:

require 'httpclient'
require 'json'

client = HTTPClient.new

# Prepare your data and convert to JSON
payload = { username: 'johndoe', email: 'john@example.com' }.to_json

# Send POST with Content-Type header
response = client.post(
  'https://your-target-api.com/endpoint',
  payload,
  { 'Content-Type' => 'application/json' }
)

Option 2: Set global default headers

If you want all requests from this client to use JSON by default, set the default_header property:

client = HTTPClient.new
client.default_header['Content-Type'] = 'application/json'
client.default_header['Accept'] = 'application/json' # Optional, but helpful for expecting JSON responses

2. Fixing the NameError: uninitialized constant JSONClient

The bad news: JSONClient isn't a built-in class in the httpclient gem—you might have confused it with another library or heard about a custom wrapper that doesn't exist out of the box.

The good news: You can easily build your own simple JSONClient wrapper to simplify JSON requests. Here's a quick example:

require 'httpclient'
require 'json'

class JSONClient
  def initialize
    @client = HTTPClient.new
    @client.default_header['Content-Type'] = 'application/json'
    @client.default_header['Accept'] = 'application/json'
  end

  # POST request with JSON payload
  def post(url, data_hash)
    response = @client.post(url, data_hash.to_json)
    JSON.parse(response.body) # Auto-parse JSON response
  end

  # Add GET, PUT, DELETE methods as needed
  def get(url)
    response = @client.get(url)
    JSON.parse(response.body)
  end
end

# Usage example
json_client = JSONClient.new
post_response = json_client.post('https://api.example.com/users', { name: 'Jane Doe' })
get_response = json_client.get('https://api.example.com/users/1')

Quick Notes:

  • Always make sure to require 'json'—it's part of Ruby's standard library, but you need to explicitly load it to use to_json and JSON.parse.
  • If you ever need to send non-JSON data with the same client, just override the header for that specific request (like passing a different headers hash to post/get).

内容的提问来源于stack exchange,提问作者user2954587

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:25:39