Ruby httparty发布请求

时间:2017-08-02 14:36:01

标签: php ruby http post httparty

我有工作的PHP代码

fileOutputStream = new FileOutputStream(outputFilePath);
GZIPOutputStream gzipOut = new GZIPOutputStream(fileOutputStream, 512000, false);
this.writer = new OutputStreamWriter(gzipOut, "UTF-8");
writer.write(line);  

我需要在ruby代码中对其进行转换

我试过了

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

但有HTTParty.post("https://myurl/api/add_lead", { :body => { first_name: "test", phone: "123456789", email: "email@email.com" , ipaddress:'192.168.0.0'}, :headers => { 'Content-Type' => 'application/x-www-form-urlencoded','charset'=>'utf-8'} }) 错误代码

如何正确地做到这一点?

2 个答案:

答案 0 :(得分:5)

请注意,在PHP代码中,您将字符串作为POST主体传递 在Ruby代码中,你传递了一个json。

尝试以下方法:

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

答案 1 :(得分:0)

对于application/x-www-form-urlencoded内容类型,请使用URI.encode_www_form(your_data)

require 'uri'

...

data = { 
  first_name: "test", 
  phone: "123456789", 
  email: "email@email.com" , 
  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)