簡體   English   中英

如何向 VK API 發送 POST 請求

[英]How to send POST requests to the VK API

我有一個需要發送長消息的 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 和 rest 中的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 個字符的消息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM