简体   繁体   中英

Post request empty response PHP curl

邮递员回答

我的答案

When trying to send a post request to the server, the response returns an empty array "{}". But there is an answer on postsman. Presumably this is related to the content type of the response

<?php

$url = "https://api.business.kazanexpress.ru/api/oauth/token? 
grant_type=password&username={}&password={}";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Authorization: Basic token",
   "Content-Type: application/json",
   "Content-Length: 0",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);

?>

Usually the OAuth2 provider will want you to send the data inside the POST body and not in the URL. To do this you can send an array with your grant_type , username and password using CURLOPT_POSTFIELDS and remove the Content-Type and Content-Length headers since cURL will generate them for you when using CURLOPT_POSTFIELDS .

It should look something like this

<?php

$url = "https://api.business.kazanexpress.ru/api/oauth/token";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, [
    'username' => '',
    'password' => '',
    'grant_type' => 'password'
]);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = [
   "Authorization: Basic token",
];

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM