【问题标题】:iOS/IBM Cloud/Swift: Post to Watson API using AlamoFireiOS/IBM Cloud/Swift:使用 AlamoFire 发布到 Watson API
【发布时间】:2018-05-30 17:37:59
【问题描述】:

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

上面的代码有什么问题?

【问题讨论】:

    标签: ios swift ibm-cloud alamofire tone-analyzer


    【解决方案1】:

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

    用户名/密码不是常规参数,但您需要将它们作为身份验证标头传递。文档为此提供了示例。这可以解释 401,因为没有向 Watson 传递任何身份验证。

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

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

    【讨论】:

    • 它似乎不允许您同时创建带有标头和参数的请求。你认为我需要提出两个请求吗?
    • 这里的关键是 .authenticate 位于 .request 之后
    猜你喜欢
    • 2017-06-28
    • 2018-11-10
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多