我正在阅读alchemy-API文档:
http://www.alchemyapi.com/api/image-tagging/image.html
他们说图像必须是URI编码的......究竟是什么意思?
是否意味着将图像转换为base64字符串,然后将其传递给请求?
我已尝试过,但收到了http 414错误 - 请求URI太大了。
以下是我的代码请求:
@IBAction func analyzeImage(sender: UIButton) {
var imageData = UIImagePNGRepresentation(mainImage.image)
let base64ImageString = imageData.base64EncodedStringWithOptions(.allZeros)
let requestString = ENDPOINT+"?apikey="+API_KEY+"&image="+base64ImageString+"&outputMode=json"
let url = NSURL(string: requestString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
}
编辑:我考虑到Dijkgraaf建议使用POST请求而不是GET来解决URI长度问题。我正在使用Alamofire库来执行此操作。这是我的代码:
@IBAction func analyzeImage(sender: UIButton) {
var imageData = UIImagePNGRepresentation(mainImage.image)
let base64ImageString = imageData.base64EncodedStringWithOptions(.allZeros)
let params = [
"apikey" : API_KEY,
"image" : base64ImageString,
"outputMode" : "json"]
var manager = Manager.sharedInstance
//Passing all the headers you want!
manager.session.configuration.HTTPAdditionalHeaders = [
"Content-Type": "application/x-www-form-urlencoded"
]
manager.request(.POST, ENDPOINT, parameters:params, encoding: .URL)
.response { (request, response, data, error) in
println(request)
println(response)
println(error)
}
}
然而,我得到一个"无法分析:下游问题"我尝试这个时出错了。
这是控制台输出:
<NSMutableURLRequest: 0x1742040c0> { URL: http://access.alchemyapi.com/calls/image/ImageGetRankedImageKeywords }
Optional(<NSHTTPURLResponse: 0x17082c1e0> { URL: http://access.alchemyapi.com/calls/image/ImageGetRankedImageKeywords } { status code: 200, headers {
"Access-Control-Allow-Origin" = "*";
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Length" = 326;
"Content-Type" = "application/json";
Date = "Mon, 08 Jun 2015 05:59:22 GMT";
Server = nginx;
"X-AlchemyAPI-CurrentVersion" = "12.15";
"X-AlchemyAPI-Error-Msg" = "cannot-analyze:downstream-issue";
"X-AlchemyAPI-Key" = [API KEY HIDDEN];
"X-AlchemyAPI-Params" = "sentiment=0&knowledgeGraph=0&detectedLanguage=unknown&submitLanguage=detect";
"X-AlchemyAPI-Status" = ERROR;
"X-AlchemyAPI-Total-Transactions" = 0;
} })
nil
不确定出现了什么问题,但Alchemy文档确实说明POST请求应该包含&#34; Content-Type&#34;标题设置为&#34; application / x-www-form-urlencoded&#34;,无论我尝试设置什么,它似乎都没有发生。这可能是问题吗?
编辑:我再次尝试POST原始图像数据,Dijkgraaf建议:
@IBAction func analyzeImage(sender: UIButton) {
var imageData = UIImagePNGRepresentation(mainImage.image)
//let base64ImageString = imageData.base64EncodedStringWithOptions(.allZeros)
var request = HTTPTask()
request.requestSerializer = HTTPRequestSerializer()
request.requestSerializer.headers["Content-Type"] = "application/x-www-form-urlencoded"
let params: Dictionary<String,AnyObject> = [
"apikey" : API_KEY,
"imagePostMode" : "raw",
"image" : imageData,
"outputMode" : "json"]
request.POST(ENDPOINT, parameters: params, completionHandler: {(response: HTTPResponse) in
println(response.headers)
})
}
但我仍然得到同样的不能 - 再次分析下游问题错误。
答案 0 :(得分:6)
使用imagePostMode raw时,需要将图像数据作为POST请求的主体发送,并且参数应包含在端点URL中(例如ENDPOINT =&#34; http://access.alchemyapi。 COM /调用/图像/ ImageGetRankedImageKeywords apikey = API_KEY&安培;输出outputmode = JSON&安培; imagePostMode =生&#34)。我还没有和Swift合作,所以我不知道最好的方法,但它与你的期望有点不同。
答案 1 :(得分:2)
下面的代码适用于我。
"defaultJSExtensions": true,
你也可以通过下面的curl命令测试Image Tagging Requst。
let image = UIImage(named: "your-image.png")
getImageTag(image!)
func getImageTag(image:UIImage){
let apiKey = "xxx-xxx-xxx-xxx-xxx"
let url = "https://gateway-a.watsonplatform.net/calls/image/ImageGetRankedImageKeywords?imagePostMode=raw&outputMode=json&apikey=" + apiKey
let myURL = NSURL(string: url)!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let imageData = UIImagePNGRepresentation(image)
request.HTTPBody = imageData!
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// Your completion handler code here
if let error = error {
print("error: \(error)")
}
print(response)
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
}
task.resume()
}