问题
I need to connect to the Microsoft Azure Machine Learning Studio Api with ruby instead of python. Can someone help me translate this python code into ruby using the net/http gem.
import urllib2
# If you are using Python 3+, import urllib instead of urllib2
import json
data = {
"Id": "score00001",
"Instance": {
"FeatureVector": {
"value_1"= "1",
"value_2"= "2",
"value_3"= "3",
"value_4"= "4",
"value_5"= "5",
"value_6"= "6",
"value_7"= "7",
"value_8"= "8",
"value_9"= "9",
"value_10"= "10",
},
"GlobalParameters":
{
}
}
}
body = str.encode(json.dumps(data))
url = 'https://appurl/score'
api_key = 'some_api_key_abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
response = urllib2.urlopen(req)
# If you are using Python 3+, replace urllib2 with urllib.request in the above code:
# req = urllib.request.Request(url, body, headers)
# response = urllib.request.urlopen(req)
result = response.read()
print(result)
How do I sent a request with net/http with three fields (url, body, headers) in ruby?
回答1:
Perhaps Unirest is a better tool for the task, its very intuitive.
require 'unirest'
data = {
"Id" => "score00001",
"Instance" => {
"FeatureVector" => {
"value_1" => "1",
"value_2" => "2",
"value_3" => "3",
"value_4" => "4",
"value_5" => "5",
"value_6" => "6",
"value_7" => "7",
"value_8" => "8",
"value_9" => "9",
"value_10"=> "10",
},
"GlobalParameters" => {}
}
}
url = 'https://appurl/score'
api_key = 'some_key'
headers = { 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' + api_key }
response = Unirest.post url, headers: headers, parameters: data
response.code
response.headers
response.body
response.raw_body
来源:https://stackoverflow.com/questions/27576426/connect-to-microsoft-azure-machine-learning-studio-api-with-ruby-instead-of-pyth