首页 > 解决方案 > 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)
            }
        }

标签: iosswiftibm-cloudalamofire

解决方案


推荐阅读