Ruby 请求小程序 API 异常

bighuzi · 2019年09月28日 · 最后由 bighuzi 回复于 2019年09月29日 · 5526 次阅读

请求的接口是腾讯特殊字符检测:https://api.weixin.qq.com/wxa/msg_sec_check ruby 请求代码

uri = URI.parse("https://api.weixin.qq.com/wxa/msg_sec_check")
 http = Net::HTTP.new(uri.host,uri.port)
 http.use_ssl = true
 http.verify_mode = OpenSSL::SSL::VERIFY_PEER
 http.cert_store = OpenSSL::X509::Store.new
 http.cert_store.set_default_paths
 req = Net::HTTP::Post.new(uri.path)
 req.set_form_data({content: "好不好呢",access_token: access_token})
 res = http.request(req)
 Rails.logger.debug res.body
 return JSON.parse(res.body)

返回错误信息:

  app/models/wechat_applet_manager.rb:41
Completed 500 Internal Server Error in 870ms (ActiveRecord: 1.8ms)
Zlib::DataError (incorrect header check):
app/models/wechat_applet_manager.rb:67:in `post_msg_sec_check'

求大神指导需要怎么处理

请求的 header 要加上 content_type: :json, accept: :json
我用的 rest client,跑起来没问题,你参考一下

response =  RestClient.post "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=#{access}", {content: message.to_s}.to_json, {content_type: :json, accept: :json}
obj = JSON.parse(response.body)
errMsg = obj['errMsg']
errcode = obj['errcode']
kxu1988 回复

请求换成 rest client 方式也改成你那种了还是有这个问题。

response =  RestClient.post "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=#{access_token}", {content: "ddksdfj"}.to_json, {content_type: :json, accept: :json}
   obj = JSON.parse(response.body)
   errMsg = obj['errMsg']
   p errcode = obj['errcode']
   app/models/wechat_applet_manager.rb:41
incorrect header check
   (0.4ms)  BEGIN

已解决:打印了 req 之后去掉‘accept-encoding’就可以了。 req = Net::HTTP::Post.new(uri)

req['accept-encoding'] = "" req['Content-Type'] = 'application/json' req['accept'] = "json"

需要 登录 后方可回复, 如果你还没有账号请 注册新账号