我试图在我的rails应用程序中做一个curl调用,用于情感分析,如下面所示,https://algorithmia.com/algorithms/nlp/SentimentAnalysis
text = "I love coding"
secret = "yv5julwo8l7biwuni62r37t823igd87d97u623568yf"
result = `curl -X POST -d '"#{text}"' -H 'Content-Type: application/json' -H 'Authorization: Simple #{secret}' https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2`
result = JSON.parse(result)但在反勾内,它没有正确地替换值。那么,如何替换这个curl命令中的变量呢?
当我用I love coding执行这段代码时,我在他们的网站上得到响应0,我得到了2 (这是正确的),这让我相信它没有正确地替换变量值。
发布于 2015-11-29 06:28:13
当使用最简单的参数进行系统调用时,您应该始终使用谢洛尔斯库来确保正确地转义和/或引用参数。例如:
require "shellwords"
text = '"I love coding"'
secret = "yv5julwo8l7biwuni62r37t823igd87d97u623568yf"
args = [ "-X", "POST",
"-d", text,
"-H", "Content-Type: application/json",
"-H", "Authorization: Simple #{secret}",
"https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2" ]
data = `curl #{args.shelljoin}`
result = JSON.parse(data)而且,正如Tin上面所指出的,backticks并不是在Ruby中进行系统调用的唯一方法,也不一定是最好的方法。我强烈建议阅读本系列文章:https://devver.wordpress.com/2009/06/30/a-dozen-or-so-ways-to-start-sub-processes-in-ruby-part-1/
最后,当rest-client、faraday和httparty等宝石可用时,对curl进行系统调用通常不是从Ruby发出HTTP请求的最佳方式,更不用说标准库中的Net::HTTP。
发布于 2015-11-28 22:02:50
我认为你的api-键有一个错误。您的代码与我的api密钥一样工作。
编辑:
代码正在工作,如下所示:

编辑2:
require 'json'
text = 'I love coding'
secret = 'secret'
result = `curl -X POST -d '"#{text}"' -H 'Content-Type: application/json' -H 'Authorization: Simple #{secret}' https://api.algorithmia.com/v1/algo/nlp/SentimentAnalysis/0.1.2`
result = JSON.parse(result)
puts resulthttps://stackoverflow.com/questions/33976467
复制相似问题