api - 如何向 VK API 发送 POST 请求
问题描述
我有一个需要发送长消息的 VK 机器人。它们不适合 URI,如果我尝试发送 GET 请求,API 会返回URI too long
错误。发送请求Content-Type: application/json
并将 json 作为正文传递是行不通的,也不可能发送Content-Type: multipart/form-data
请求。是否可以向 VK API 发送 POST 请求?
解决方案
可以使用 发送 POST 请求Content-Type: application/x-www-form-urlencoded;charset=UTF-8
。此外,建议在 url 中发送access_token
和v
参数,其余部分在正文中。
JavaScript 中的示例:
const TOKEN = '...'
const VERSION = '5.126'
fetch(`https://api.vk.com/method/messages.send?access_token=${TOKEN}&v=${VERSION}`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
random_id: Math.round(Math.random()*100000),
peer_id: 185014513,
message: 'Hello world'
}).toString()
})
.then((res) => res.json())
.then(console.log)
在 PHP 中:
const TOKEN = '...';
const VERSION = '5.126';
$query = http_build_query([
'access_token' => TOKEN,
'v' => VERSION,
]);
$body = http_build_query([
'random_id' => mt_rand(0, 100000),
'message' => 'Hello world',
'peer_id' => 185014513,
]);
$url = "https://api.vk.com/method/messages.send?$query";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER , [
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
]);
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response, true);
请注意,您不能发送超过 4096 个字符的消息
推荐阅读
- python - 如何计算列表中重复的出现和数量?
- wordpress - Worpress 联系表 7 wpcf7_before_send_mail Bcc 字段
- selenium - 找到对象但未发生单击
- datatable - primeng 数据表单元格编辑器未编辑正确的单元格
- sql - 将结果截断到小数点后两位,并在 SQL Server 中将它们四舍五入到下一个整数百分比
- plugins - XD Plugin Develop:列出库颜色、字符样式、符号
- google-bigquery - 如何使用摄取分区表在 BQ 命令行中设置大查询需要分区过滤器
- python - 如何将儒略日期转换为日历日期?
- java-8 - Guava 缓存异步重载
- http - Golang net/http 服务器处理程序热重载