新手问题 用了融云的消息推送,遇到一个很苦闷的错误

xiaobai2 · 2016年08月31日 · 最后由 lisafangfang 回复于 2019年05月14日 · 4400 次阅读
def send_from_rong
    rc_rand = rand(100000)
    time = Time.now.to_i
    sign = signature({'rc_rand' => rc_rand, 'time' => time})
    headers = {"RC-App-Key" => Rails.application.secrets.rongcloud.try(:[], "app_key"),
      "RC-Nonce" => rc_rand.to_s, "RC-Timestamp" => time.to_s, 'RC-Signature' => sign.to_s,
      "Content-Type" => "Application/x-www-form-urlencoded"}
    body = (os == 'all' ? {
      'fromUserId' => sendor_id, 'objectName' => object_name, 'content' => content, 'pushContent' => push_content, 'pushData' => push_data} : {
        'fromUserId' => sendor_id, 'objectName' => object_name, 'content' => content, 'pushContent' => push_content, 'pushData' => push_data, 'os' => os})
    response = HTTParty.post("https://api.cn.ronghub.com/message/broadcast.json", {
      body: body,
      headers: headers
    })
    if response['code'] == 200
      self.status = 1
      self.save
    end
  end

现在 response 对象一直报如下错误:

#<HTTParty::Response:0x7f806c6c8e98 parsed_response={"url"=>"/message/broadcast.json", "code"=>1002, "errorMessage"=>"Parameter content should be JSON format."}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>["Wed, 31 Aug 2016 03:28:17 GMT"], "content-type"=>["application/json"], "content-length"=>["103"], "connection"=>["close"]}>

然后我给 body.to_json 之后如下错误:

#<HTTParty::Response:0x7f80748ebe48 parsed_response={"url"=>"/message/broadcast.json", "code"=>1002, "errorMessage"=>"content is required."}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>["Wed, 31 Aug 2016 03:28:45 GMT"], "content-type"=>["application/json"], "content-length"=>["83"], "connection"=>["close"]}>

奇怪啊,我的 content 明明已经有了,为什么还让我加呢?求大神指点

来。用我的 gem 吧rongcloud-ruby

你这个问题解决办法是吧 content 转换成 json 格式。之前遇到过这个问题

是只给 content 转成 json body 不变。

#1 楼 @hging 直接把 body 里边的 content to_json 就行了吗?如下:

body = ({
        'fromUserId' => sendor_id, 'objectName' => object_name, 'content' => content.to_json, 'pushContent' => push_content, 'pushData' => send_date})

#2 楼 @xiaobai2 对的。是这样 你尝试下。可以看看我的 gem 虽然写的不怎么样。但是封装了下用起来方便。

可还是不对啊,content.to_json 之后还是和之前一样

抱歉 我刚才尝试了下 之前的信息是针对单聊的 然后这个错误想要解决是把 body 改成如下内容

body = ({
        'fromUserId' => sendor_id, 'objectName' => object_name, 'content' => {content: content}.to_json, 'pushContent' => push_content, 'pushData' => send_date})

#5 楼 @hging 谢谢!解决了

#5 楼 @hging 另外再问大神一个问题,为什么我发送的消息总是延迟很长时间呢?难道是融云那边儿有限制吗?我的测试用户数 140 左右

#7 楼 @xiaobai2 这个就真不知道了。你联系下融云的客服。

#8 楼 @hging 好的,谢谢了😀

推荐使用第三方 MobPush 这个,本人曾经使用过,觉得很不错,集成起来较方便,而且他们有很多的服务!

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