使用HTTParty发送数组作为POST请求体时出现bytesize未定义错误该如何解决?
解决HTTParty发送数组请求体时的
bytesize错误 这个错误的根源很明确:你直接把Ruby数组传给了:body参数,但HTTParty默认不会自动将数组序列化为JSON字符串,而底层的Net::HTTP需要的是字符串形式的请求体——数组没有bytesize方法,自然就报错了。而Postman能成功,是因为它帮你自动完成了「数组转JSON字符串」+「设置正确Content-Type头」这两步。
给你两个靠谱的解决方案:
方案1:手动序列化数组为JSON字符串
直接调用Ruby数组的to_json方法,把它转换成JSON格式的字符串,同时确保Content-Type头设置为application/json:
require 'json' # 确保已经引入json库 response = HTTParty.post( App.base_uri + "/api?service=post&action=update&version=2", body: [{"some_big_json": "with many key value pair"}].to_json, headers: { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Cookie' => @@cookie } )
方案2:使用HTTParty的:json参数(更推荐)
HTTParty提供了:json参数,它会自动帮你完成序列化操作,还能自动设置Content-Type: application/json头,代码更简洁,也不容易出错:
response = HTTParty.post( App.base_uri + "/api?service=post&action=update&version=2", json: [{"some_big_json": "with many key value pair"}], headers: { 'Accept' => 'application/json', 'Cookie' => @@cookie } )
不管用哪种方案,核心都是让请求体以JSON字符串的形式发送,这样后端就能像Postman请求那样正确解析数组内容了。
内容的提问来源于stack exchange,提问作者suhasa
相关产品推荐
相关产品推荐

