【发布时间】:2020-12-09 11:36:06
【问题描述】:
我有一个需要发送长消息的 VK 机器人。它们不适合 URI,如果我尝试发送 GET 请求,API 会返回 URI too long 错误。使用Content-Type: application/json 发送请求并将json 作为正文传递是行不通的,也不能发送Content-Type: multipart/form-data 请求。是否可以向 VK API 发送 POST 请求?
【问题讨论】:
我有一个需要发送长消息的 VK 机器人。它们不适合 URI,如果我尝试发送 GET 请求,API 会返回 URI too long 错误。使用Content-Type: application/json 发送请求并将json 作为正文传递是行不通的,也不能发送Content-Type: multipart/form-data 请求。是否可以向 VK API 发送 POST 请求?
【问题讨论】:
可以使用Content-Type: application/x-www-form-urlencoded;charset=UTF-8 发送POST 请求。另外建议在 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 个字符的消息
【讨论】: