2

Say I have the following curl call :

"curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate"

I'm trying to get the output of the curl call. Such as the 200 OK or 404 ERROR status.

So, if I do :

a = `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

I get nothing back in a

However, if I do

puts `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

Then I can see the output. How do I read it into the variable. I'd prefer an answer without any import like OPEN3, if possible.

4

3 回答 3

3

我不知道为什么

a = `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

不适合你。

这是我通过更简单的测试得到的结果:

RUBY_VERSION # => "1.9.3"

`curl --version`
# => "curl 7.30.0 (x86_64-apple-darwin13.0) libcurl/7.30.0 SecureTransport zlib/1.2.5\nProtocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp \nFeatures: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz \n"

a = `curl http://echo.jsontest.com/hello/world`

a # => "{\"hello\": \"world\"}\n"

更新

我错过了您问题的一部分,没有意识到您正在寻找标题。

尝试这个:

a = `curl -I http://echo.jsontest.com/hello/world`
a.lines.first # => "HTTP/1.1 200 OK\r\n"

希望这会有所帮助。

于 2014-03-27T22:34:37.383 回答
1

您可能只想使用Ethon与 libcurl 交互,而不是调用 shell 接口,特别是如果您不愿意使用 Ruby 提供的工具来更容易地与 shell 和其他进程交互(你知道,比如Open3) .

注意:Ruby 标准库(包括 Open3)是 Ruby 的一部分并随它一起分发。这绝不是一种导入,但如果您出于某种愚蠢的原因真的不想使用该require方法,IO则无需加载其他代码即可使用,并提供 Open3 使用的低级接口。

于 2014-03-27T00:07:44.663 回答
1

尝试这个:

HTTP_RESP_CODE=$(curl -s -o out.html -w '%{http_code}' http://www.example.com)

echo $HTTP_RESP_CODE

这适用于我的ruby.

HTTP_RESP_CODE=`curl -s -o out.html -w '%{http_code}' http://www.example.com`
print HTTP_RESP_CODE
于 2014-03-27T08:06:27.797 回答