Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby httparty post request

I have working php code

   <?php
    $ch = curl_init("https://myurl/api/add_lead");

    $first_name = $_POST["name"];
    $phone = $_POST["phone"];
    $email = $_POST["email"];
    $ipaddress = $_SERVER['REMOTE_ADDR'];

    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1120);

    curl_setopt($ch,CURLOPT_POSTFIELDS,"first_name=$first_name&phone=$phone&email=$email&ipaddress=$ipaddress");
    curl_setopt($ch,CURLOPT_HTTPHEADER,["Content-Type:application/x-www-form-urlencoded; charset=utf-8"]);

    curl_setopt($ch,CURLOPT_TIMEOUT,60);
    $result = curl_exec($ch);

    curl_close($ch);
    ?>

I need to transform it in ruby code

I have tried

HTTParty.post("https://myurl/api/add_lead",
{
:body => { first_name: "test", phone: "123456789", email: "[email protected]" , ipaddress:'192.168.0.0'},
:headers => {  'Content-Type' => 'application/x-www-form-urlencoded','charset'=>'utf-8'}

})

but have got 500 error code

How to do it properly?

like image 783
user8338151 Avatar asked Dec 18 '22 05:12

user8338151


2 Answers

Note that in your PHP code, you're passing a string as the POST body.
In Ruby code, you're passing a json.

Try the following:

HTTParty.post("https://myurl/api/add_lead", {
  body: "first_name=test&phone=123456789&[email protected]&ipaddress=192.168.0.0",
  headers: {
    'Content-Type' => 'application/x-www-form-urlencoded',
    'charset' => 'utf-8'
  }
})
like image 142
Lucas Costa Avatar answered Jan 04 '23 19:01

Lucas Costa


For application/x-www-form-urlencoded Content-Type use URI.encode_www_form(your_data):

require 'uri'

...

data = { 
  first_name: "test", 
  phone: "123456789", 
  email: "[email protected]" , 
  ipaddress:'192.168.0.0'
}

authorization_string = "#{ENV['API_KEY']}:#{ENV['API_SECRET']}"
url = "https://myurl/api/add_lead"

response = HTTParty.post(url,
  body: URI.encode_www_form(data),
  headers: { 
    'Content-Type' => 'application/x-www-form-urlencoded', 
    'Authorization' => "Basic #{Base64.strict_encode64(authorization_string)}" 
  }
)

response_body = JSON.parse(response.body)
like image 20
31113 Avatar answered Jan 04 '23 19:01

31113