Alex
Alex

Reputation: 159

Net::HTTP::Post.new request returns empty body in Ruby 2

In Ruby 2.0.0p195, Rails 4.0.0, Net::HTTP::Post.new request returns empty body of response.

    @toSend = {
        "zuppler_store_id" => 'X3r82l89',
        "user_id" => '1'
    }.to_json

    uri = URI("http://smoothpay.com/zuppler/gen_token_post.php")
    http = Net::HTTP.new(uri.host,uri.port)

    req = Net::HTTP::Post.new uri
    req.content_type = "application/json"   
    req.body = @toSend   # or "[ #{@toSend} ]" ?

    res = Net::HTTP.start(uri.host, uri.port) {|http| http.request(req)}

    puts "Response #{res.code} - #{res.message}: #{res.body}"

This code returns "Response 200 - OK:"

But it should return like this: {"result":"success","token":"843e5be88fb8cee7d324244929177b4e"}

You can check it by typing this url: http://smoothpay.com/zuppler/gen_token_test.php

Why is res.body empty?

Upvotes: 1

Views: 2016

Answers (1)

DiegoSalazar
DiegoSalazar

Reputation: 13531

Seems like that service doesn't like the POST request to be application/json.

This works:

uri = URI("http://smoothpay.com/zuppler/gen_token_post.php")
http = Net::HTTP.new(uri.host,uri.port)

req = Net::HTTP::Post.new uri
req.body = "zuppler_store_id=X3r82l89&user_id=1"

res = Net::HTTP.start(uri.host, uri.port) {|http| http.request(req)}

res.body # => "{\"result\":\"success\",\"token\":\"9502e49d454ab7b7dd2699a26f742cda\"}"

In other words, give the service application/x-www-form-urlencoded. Peculiarly, it will hand you back text/html which you'll have to JSON.parse. Weird service.

Upvotes: 2

Related Questions