0

我需要一些帮助将 php 脚本翻译成 ruby

php脚本:

$apiUrl = 'http://someurl/' . $_POST['type'];
unset($_POST['type']);

$fields = $_POST;
$fields['ip'] = $_SERVER['REMOTE_ADDR'];
$fieldsString = http_build_query($fields);

$ch = curl_init();

////set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Api-Key: somekey'
));
curl_setopt($ch,CURLOPT_URL, $apiUrl);
curl_setopt($ch,CURLOPT_POST, count($fieldsString));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fieldsString);
echo "<pre>";
var_dump($fields);
////execute post
$result = curl_exec($ch);
////close connection
curl_close($ch);
exit;

到目前为止我所做的红宝石代码..

postparams = {
    'sent_from'         => 2,
    'id'                => @client.id,
    ...etc...
    'type'              => type,
    'ip'                => request.remote_ip
}

apiUrl = "http://someurl/#{type}"
fields = postparams

#$fieldsString = http_build_query($fields);
fieldsString = fields.to_query

#$ch = curl_init();
easy = Curl::Easy.new
#curl_setopt($ch,CURLOPT_HEADER, true);

# curl_setopt($ch, CURLOPT_HTTPHEADER, array(
#     'Api-Key: somekey'
# ));
easy.headers = ["Api-Key: somekey"]
#curl_setopt($ch,CURLOPT_URL, $apiUrl);
easy.url     = apiUrl
#curl_setopt($ch,CURLOPT_POST, count($fieldsString));

#curl_setopt($ch,CURLOPT_POSTFIELDS, $fieldsString);
res = easy.http_post(apiUrl, fieldsString)

#$result = curl_exec($ch);

render :text => res.inspect

所以问题是:

  • 我如何翻译 #curl_setopt($ch,CURLOPT_POST, count($fieldsString));
  • 我如何翻译 #curl_setopt($ch,CURLOPT_HEADER, true);
  • easy.http_post 会执行我打算执行的操作吗?那是发布带有给定标题选项的参数等...
  • 任何其他建议

谢谢

4

1 回答 1

1

我如何翻译 #curl_setopt($ch,CURLOPT_HEADER, true);

像这样:

 easy.header_in_body = true

我如何翻译 #curl_setopt($ch,CURLOPT_POST, count($fieldsString));

php curl_setopt() 文档说:

CURLOPT_HTTPGET TRUE

将 HTTP 请求方法重置为 GET。由于GET 是默认设置,因此只有在请求方法已更改时才需要这样做。

换句话说,如果你写:

curl_setopt($ch,CURLOPT_POST, FALSE);

该请求默认为获取请求。所以...

http_method = (postparams.length==0) ? 'get' : 'post'
easy.http(http_method)
于 2013-07-02T11:44:19.590 回答