如何向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_tokenv参数,其余参数在正文中发送。

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个字符长的消息

最新更新