我正在阅读这里的炼金术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,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请求应该将“Content-Type”标题设置为“application / x-www-form-urlencoded”,这似乎不会发生,无论什么我试着设定.这可能是问题吗?
编辑:我再次尝试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) }) }
但我仍然得到相同的不能 – 再次分析下游问题错误.