ios - IOS/Swift/Bluemix:将 curl 请求转换为 IBM Watson 到 Swift 中的 AlamoFire 请求
问题描述
我可以使用以下使用 CURL 用 PHP 编写的代码从网页访问 Watson Tone Analyzer API:
$username='long-user-name';
$password='my-password';
$data = json_encode(array('text' => 'All you need is love'));
$URL = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
IBM/Watson 没有提供通过 Swift 或 AlamoFire for IOS 访问 API 的示例代码,尽管他们的 Swift SDK 显然使用了 AlamoFire。我没有下载他们的 SDK,因为它需要 carthage 并且具有人们报告为导致问题的其他依赖项。但是,您应该能够使用 AlamoFire 请求 API。
我尝试的以下代码给出了错误身份验证的 401 错误。IBM Bluemix 团队或其他地方的任何人都可以建议如何将上述工作 curl 转换为有效的 AlamoFire 请求吗?在此先感谢您的任何建议。
我的代码返回 401 错误的身份验证:
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-username",
"password":"my-password"]
parameters["text"] = message
Alamofire.request(url, parameters: parameters)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.result)
}
}
解决方案
推荐阅读
- python - Shopify Python API:如何将产品列表序列化为 JSON?
- python - KIVY:如何使用 on_touch_down 进入第二个屏幕?
- unnest - Nextflow“扁平化”类似于 dplyr 中的“unnest”
- database - 谷歌表格代码从一行复制公式并粘贴到下一个空行中,然后从前一行中删除公式但保留结果?
- tensorflow - 使用 TensorFlow 获取数据并应用交叉验证
- java - JavaFX - 媒体播放器
- python - Pandas 数据框中的日期字段比较问题
- typescript - Redux Sagas Call 未调用传递给它的函数
- java - java可调用多种方法
- django - 如何在 Django 管理操作中使用 queryset.update?