Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request to HTTPS using Net::HTTP

This POST request using Ajax works perfectly:

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");

I need to have the same request but in Ruby. I tried with Net:HTTP, but it doesn't work and I don't get any error so I can't debug it:

    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

How should I proceed to get the error or where did I go wrong ?

like image 973
Graham Slick Avatar asked Apr 13 '16 14:04

Graham Slick


1 Answers

Your request hash is being replaced by your request object which you're assigning Net::HTTP. Also be sure to set request params in the body of your HTTP request:

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)

You may find the following reference helpful: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html

like image 129
Anthony E Avatar answered Oct 04 '22 23:10

Anthony E