POST request to HTTPS using Net::HTTP
Asked Answered
B

1

5

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 ?

Barytes answered 13/4, 2016 at 14:43 Comment(0)
K
9

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

Kokaras answered 13/4, 2016 at 14:58 Comment(8)
Thanks for your help. However, I still don't get anything. I don't have any error, and nothing happens on facebook.Barytes
Why did you remove the .to_json ?Barytes
Form encoding should be handled Net::HTTP internally.Kokaras
What response are you getting? Is the body of the respons blank? If so, what's the status code?Kokaras
Well that's the problem, I'm not getting any response. I try it from my console: curl -X POST localhost:3000/webhook and nothing happensBarytes
(this code is in my webhook_post action which is set to accept post requests in my routes)Barytes
Ok, I'd run the above code independently to isolate the issue. What happens if you run the above code directly from the console?Kokaras
Let us continue this discussion in chat.Kokaras

© 2022 - 2024 — McMap. All rights reserved.