【发布时间】:2019-07-08 19:53:34
【问题描述】:
我需要在使用 Ruby 的 Post 请求正文中包含图像。该示例使用 Bing Visual Search API 来查找与帖子正文中发送的图像相似的图像。我得到了一个结果,但它是空的 JSON。设置 Post 正文的代码显然有问题。我是 Ruby 语言的新手。
帖子正文中的文本边界必须包含在图像数据中。我知道查询有效,因为我可以使用 C# 或 Java 发送相同的请求并获得结果。我已经尝试对图像数据进行 base64encode 并简单地将文件读入 Post 数组。
# include libs
require 'net/https'
require 'uri'
require 'json'
require 'base64'
accessKey = "Access_Key_String"
uri = "https://api.cognitive.microsoft.com"
path = "/bing/v7.0/images/visualsearch"
batchNumber = "097ad727-862d-4720-93c4-08f7038cea7c"
fileName = "ElectricBike.jpg"
if accessKey.length != 32 then
puts "Invalid Bing Search API subscription key!"
puts "Please paste yours into the source code."
abort
end
def BuildFormDataStart(batNum, fileName)
startBoundary = "--batch_" + batNum
return startBoundary + "\r\n" + "Content-Disposition: form-data;
name=\"image\"; filename=" + "\"" + fileName + "\"" + "\r\n\r\n"
end
def BuildFormDataEnd(batNum)
return "\r\n\r\n" + "--batch_" + batNum + "--" + "\r\n"
end
# Construct the endpoint uri.
uri = URI(uri + path)
# Load the parts of the post body into an array.
post_body = []
# Add the file Data
post_body << BuildFormDataStart(batchNumber, fileName)
post_body << File.read(fileName) #Base64.encode64(File.read(fileName))
post_body << BuildFormDataEnd(batchNumber)
# Create the HTTP objects
header = {'Ocp-Apim-Subscription-Key': accessKey}
# Create the request.
request = Net::HTTP::Post.new(uri, 'knowledgeRequest' => "KnowledgeRequest")
request['Ocp-Apim-Subscription-Key'] = accessKey
request.content_type = "multipart/form-data; boundary=batch_" + batchNumber
request.body = post_body.join
# Send the request and get the response.
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts "\nRelevant Headers:\n\n"
response.each_header do |key, value|
# Header names are lower-cased.
if key.start_with?("bingapis-") or key.start_with?("x-msedge-") then
puts key + ": " + value
end
end
puts "\nJSON Response:\n\n"
puts JSON::pretty_generate(JSON(response.body))
Ruby 结果为空,但在线 C# 示例有效:
https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/quickstarts/csharp
"tags": [
{
"displayName": "",
"actions": [
{
"actionType": "MoreSizes"
},
{
"actionType": "ImageById"
}
]
}
],
"image": {
"imageInsightsToken": ""
}
【问题讨论】: