Search code examples
phpjsonruby-on-rails-4net-http

Rails send four backslashes using Net::HTTP


My rails application need to send some data to a php application, which expects a POST call. I use the folowing code:

uri = URI.parse(apiUrl)
req = Net::HTTP::Post.new(uri.to_s, initheader = {'Content-Type' =>'application/json'})

req.basic_auth(api_key, token)
req.set_form_data({"action" => action, "data" => data})

http = Net::HTTP.new(uri.host, uri.port)
response = http.request(req)

Where data is a hash converted to json:

data = {
  :key1 => val1,
  :key2 => val2
}.to_json

(it is a nested hash, i.e. some values are hash as well)

My problem is that the php application receives 4 backslashes before each quotation mark:

$data_json = $_POST['data'];
error_log($data_json);

and in error log I see:

'{\\\\"key1\\\\":val1,\\\\"key2\\\\":\\\\"val2\\\\"}'

Looks like rails add one of them, but even if I remove it and replace it with the following code:

a.gsub!(/\"/, '\'')

I still get many backslashes inside the php application, hence cannot convert the string to array.

Any idea??


Solution

  • By using set_form_data net/http is POSTing the form as urlencoded. Its NOT posting your request body as pure JSON.

    If you want to POST raw JSON you will need to follow a pattern like:

    uri = URI('https://myapp.com/api/v1/resource')
    req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
    req.body = {param1: 'some value', param2: 'some other value'}.to_json
    res = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
    end