首页 > 解决方案 > 无法访问 IBM Tone Analyzer API?

问题描述

我正在尝试在 Laravel 应用程序中使用 Tone Analyzer API。无论我尝试什么,我总是得到相同的响应{"code":401, "error": "Unauthorized"}。我怀疑我的问题是我无法弄清楚如何传递 API 密钥,但官方文档没有任何帮助,因为它只包含在命令行中使用 cURL 的说明。我的代码目前看起来像这样(尽管我已经尝试了许多其他迭代。如果有人需要我,我也可以发布所有其他不成功的尝试):

$response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
        ->withOption('HTTPHEADER', array(
            'Content-Type: application/json',
            'apikey: REDACTED'))
        ->withData(array('text' => $text))
        ->asJson()
        ->post();

我正在运行 Laravel 5.8 并使用 Ixudra 的 cURL 库。如果答案也使用这个库,我更愿意,但老实说,在这一点上,我已经准备好放弃并使用 vanilla PHP,所以任何答案都会受到赞赏。

Ninja 编辑:我知道问题不在于我的帐户/API 密钥,因为我尝试通过命令行访问 API 并且它按预期工作。该问题仅在尝试从 Laravel 访问它时出现。

标签: laravelphp-curltone-analyzer

解决方案


IBM Watson Services 使用 HTTP Header Authentication 的Basic格式。因此,curl在终端中使用,你应该-u or --user以格式传递标志user:password,或者你也可以以模式发送Authentication Http Header Basic user:password:。

通过调整第二种形式的代码,您可以执行以下操作:

$response = Curl::to('https://gateway-wdc.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false')
        ->withHeader('Content-Type: application/json')
        ->withHeader('Authorization: Basic apikey:YOUR_TOKEN_HERE')
        ->withData(array('text' => $text))
        ->asJson()
        ->post();

替换YOUR_TOKEN_HERE为您的 Tone Analyzer API 访问令牌。

https://developer.mozilla.org/docs/Web/HTTP/Authentication https://www.ibm.com/support/knowledgecenter/en/SSGMCP_5.3.0/com.ibm.cics.ts.internet.doc/topics /dfhtl2a.html

希望这可以帮助!


推荐阅读