iOS/IBM 云/swift : Post to Watson API using AlamoFire

标签 ios swift ibm-cloud alamofire tone-analyzer

我正在尝试使用 AlamoFire 和以下代码发布到 Watson 音调分析器 API。它不断收到 401 错误,这显然意味着授权失败。然而,相同的用户 ID/密码信息可以通过 curl 请求找到。所以问题似乎不在于用户 ID/密码,而在于我如何形成 AlamoFire 请求。

 func postToWatson () {
        print("post to watson called")
        let url: String =  "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19"
        let message = "All you need is love"
        var parameters = [
           "username":"my-lengthy-username",
            "password":"my-ugly-password"]
        parameters["text"] = message
        Alamofire.request(url, parameters: parameters)
            .responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
        }
    }

以下是我通过上述打印命令从 API 返回的内容:

Optional(https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19&password=xxxxxx&text=All%20you%20need%20is%20love&username=xxxxxxxxxxxx)
Optional(<NSHTTPURLResponse: 0x1740396a0> { URL: https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19&password=xxxxxx&text=All%20you%20need%20is%20love&username=xxxxxxxxxxxx } { status code: 401, headers {
    Connection = close;
    "Content-Encoding" = gzip;
    Date = "Wed, 30 May 2018 17:23:30 GMT";
    "Strict-Transport-Security" = "max-age=31536000;";
    "Www-Authenticate" = "Basic realm=\"IBM Watson Gateway(Log-in)\"";
    "X-Backside-Transport" = "OK OK,FAIL FAIL";
    "X-DP-Transit-ID" = "gateway02-1020566241";
    "X-DP-Watson-Tran-ID" = "gateway02-1020566241";
    "X-Global-Transaction-ID" = ffea405d5b0ede123cd49ae1;
    "x-dp-local-file" = true;
} })
SUCCESS

上面的代码有什么问题?

最佳答案

我没用过 AlamoFire,但看看他们的 documentation for making a request the authentication处理方式与您的代码不同。

用户名/密码不是常规参数,但您需要将它们作为身份验证 header 传递。文档有相应的示例。这可以解释 401,因为没有身份验证传递给 Watson。

未经测试,但像这样的东西应该可以工作:

 Alamofire.request(url)
    .authenticate(user: username, password: password)
    .responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
}

关于iOS/IBM 云/swift : Post to Watson API using AlamoFire,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610581/

相关文章:

ios - 等待 10 秒后未能返回。主运行循环模式 : kCFRunLoopDefaultMode

ios - UITableViewCell 不会成为第一响应者(在单元格手势上显示 UIMenuController)

ios - "type of expression is ambiguous without more context"- 引用 appDelegate

kubernetes - 如何将 Kubernetes 与 IBM bluemix 容器一起使用

swift - 带有 NodeJs 的 IBM Bluemix 对象存储服务的临时公共(public) URL

database - 如何从 Cloudant 数据库中删除所有文档,甚至删除 Bluemix 中的数据库

ios - 如何将 UIButton 与自定义类一起使用?

ios - 如何使用 watchkit 应用程序从命令行生成 .ipa 文件

swift - 在 iOS 中将多个图像上传到 FTP 服务器

ios - 在 Swift 中以编程方式在两个 subview 之间添加约束