laravel - 无法访问 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 访问它时出现。
解决方案
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
希望这可以帮助!
推荐阅读
- javascript - 如何将 html 插入到 FusionCharts 标签中?我想添加一个复选框
- node.js - 尝试解析请求正文时,POST 请求挂起(超时),在 Firebase Cloud Functions 上运行 Koa
- sql - MSSQL 中是否有“通配符除外”功能?
- tabs - 以编程方式快速更改标签栏
- owl - 在 OWL 中创建具有多个限制的推断关系
- javascript - 如何在 React.js 上创建 youtube 组件列表
- python - 如何动态打印存储在 dict 值中的函数名称?
- google-cloud-platform - 如何将记录插入 BigQuery 链接服务器
- python - 如何将“令牌”作为标头从 GUI 应用程序发送到烧瓶服务中的 GET 命令?
- java - 如果条件取决于当前值和先前值,我如何检查 takeWhile 中的条件?