poJson = {
"button":[
{
"type":"click",
"name":"sing",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"favor",
"key":"V1001_GOOD"
}]
}]
}
uri = URI('https://api.weixin.qq.com/cgi-bin/token')
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
hash = JSON.parse res.body
uri = URI("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=#{hash["access_token"]}")
res = Net::HTTP.post_form(uri, "data" => poJson)
"{\"errcode\":40016,\"errmsg\":\"invalid button size hint: [dX4b8a0899vr22]\"}"
但是在微信接口测试工具里测试成功。
换用 rest-client 解决了问题
gem 'rest-client', '~> 2.0'
require 'rest-client'
RestClient.post(url, payload.to_json)
提交成功
返回码:
"{\"errcode\":0,\"errmsg\":\"ok\"}"
##中文问题
重新 post 一个带有中文的 json
返回错误码:
"{\"errcode\":40033,\"errmsg\":\"invalid charset. please check your request, if include \\\\uxxxx will create fail! hint: [xGNora0471vr20]\"}"
按照社区里的方法
require 'rest-client'
pj = {"button": buttons}
payload = pj.to_json.gsub!(/\\u([0-9a-z]{4})/) { |s| [$1.to_i(16)].pack("U") }
payload = pj.to_json if payload.blank?
RestClient.post(url, payload)
缺少这一行
payload = pj.to_json if payload.blank?
有时候会报错误码:
"{\"errcode\":44002,\"errmsg\":\"empty post data hint: [FQ_D_0824vr18]\"}"
在本地 rails c
调用"中文".to_json
解析中文很正常,为什么 post 过去就变成'\uxxxx'了。
为什么用'net/http'标准库 post 就不行了。
我用Net::HTTP.post_form(uri, "data" => data)
post 到了本地,
p params["data"]
显示输出
"{\"button\":[{\"type\":\"click\",\"name\":\"xxx\",\"key\":\"18\"}]}"
看着都很正常。
问题到底是出在了哪里。