POST 使用 Net::HTTP 请求 HTTPS

POST request to HTTPS using Net::HTTP

使用 Ajax 的 POST 请求完美运行:

var token = "my_token";

function sendTextMessage(sender, text) {
  $.post('https://graph.facebook.com/v2.6/me/messages?',
    { recipient: {id: sender}, 
      message: {text:text},
      access_token: token
    },
    function(returnedData){
         console.log(returnedData);
  });
};

sendTextMessage("100688998246663", "Hello");

我需要相同的请求,但在 Ruby 中。我试过 Net:HTTP,但它不起作用,我没有收到任何错误,所以我无法调试它:

    token = "my_token"
    url = "https://graph.facebook.com/v2.6/me/messages?"
    sender = 100688998246663
    text = "Hello"
    request =  {
                 recipient: {id: sender},
                 message: {text: text},
                 access_token: token
                }.to_json


  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new(uri.request_uri)

  response = http.request(request)
  response.body

我应该如何处理错误或哪里出错了?

您的 request 哈希将被您分配的 request 对象替换 Net::HTTP。还要确保在 HTTP 请求的正文中设置请求参数:

require "active_support/all"
require "net/http"

token = "my_token"
url = "https://graph.facebook.com/v2.6/me/messages?"
sender = 100688998246663
text = "Hello"
request_params =  {
  recipient: {id: sender},
  message: {text: text},
  access_token: token
}
request_header = { 'Content-Type': 'application/json' }

uri = URI.parse(url)

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(uri.path, request_header)
request.body = request_params.to_json

http.request(request)

response = http.request(request)

您可能会发现以下参考资料有帮助:http://www.rubyinside.com/nethttp-cheat-sheet-2940.html