您好
请帮帮我。
我正在尝试使用 Discourse API 创建一个主题,但每次尝试都会失败。这是我的代码:
https://myDiscourse.com/posts.json?title=New+test+posted&raw=new+posted+text+to+test+creation+by+api&category=45&api_key=xxxxxxxxxxxxxxxxxxxxxxxx&api_username=admin
我不知道哪里出错了,您能帮帮我吗?
谢谢
您好
请帮帮我。
我正在尝试使用 Discourse API 创建一个主题,但每次尝试都会失败。这是我的代码:
https://myDiscourse.com/posts.json?title=New+test+posted&raw=new+posted+text+to+test+creation+by+api&category=45&api_key=xxxxxxxxxxxxxxxxxxxxxxxx&api_username=admin
我不知道哪里出错了,您能帮帮我吗?
谢谢
您不能在 URL 中包含 API 密钥(这会向任何能看到您网络流量的人暴露您的密钥)。密钥必须在标头中传递。
请参阅 Grant a custom badge through the API 获取示例。
您好 @pfaffman
感谢您的帮助。我按照示例操作,但出现了一个错误:
401 Authorization Required
我的脚本:
$apikey = "xxxxxxxxxxxxxxxxxxxx";
$username = "xxxxxxxxxxxxxxxxx";
$title = "test";
$raw = "message";
$category = 9;
$url = 'https://myDiscourse.com/posts.json';
$post_fields = array(
'title' => $title,
'raw' => $raw,
'category' => $category,
);
$headers = array("Content-Type: multipart/form-data;","Api-Key: $apikey","Api-Username: $username",);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $post_fields ) );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec( $ch );
if ( curl_errno( $ch ) !== 0 ) {
echo 'Error:' . curl_error($ch);
}
curl_close( $ch );
我肯定犯了一个错误,但我不知道是什么。您能帮帮我吗?
谢谢
感谢你的代码。在不看到所有代码的情况下,很难完全调试它。我建议在脚本之外查询 API。例如,你可以使用 curl
curl -X GET "https://mydiscourse.com/posts.json" \
-H "Api-Key: 714552c6148e1617aeab526d0606184b94a80ec048fc09894ff1a72b740c5f19" \
-H "Api-Username: michael"
如果你不熟悉命令行或使用 curl,我建议使用 Postman 来调试 API 问题。对我来说,Postman 是开发人员在测试或构建 API 时必不可少的工具。
这是一个已经设置好 Discourse 路由的 Postman 工作区。只需配置你的 API 密钥和用户名。
Discourse API Documentation Postman API Network