V
V
Vyacheslav Shevchenko2018-06-19 14:45:14
1C-Bitrix
Vyacheslav Shevchenko, 2018-06-19 14:45:14

How to send post data in bitrix via Bitrix\Main\Web\HttpClient?

Good afternoon.
I'm trying to make a post request via Bitrix\Main\Web\HttpClient. The request passes, but for some reason the data is not sent.
The code:

use Bitrix\Main\Web\HttpClient;
$key = "ТУТ МОЙ КЛЮЧ ОТ АПИ https://tinypng.com/developers";
$httpClient = new HttpClient(array(
    "waitResponse" => true
));
$httpClient->setAuthorization('api', $key);
$httpClient->setHeader('Content-Type', 'application/json', true);
$url = "https://bretel.kz/upload/iblock/ecd/ecd423080780dbae80bb088c911257e8.jpg";
$data = json_encode(array("source" => array("url" => $url)));
$response = $httpClient->post('https://api.tinify.com/shrink', $data);
var_dump($data);
var_dump($response);

In response from the service, I get an error: "Request is invalid: request body has unknown key 'source'"
Although if you do the same through postMan, then the answer comes normally. PostMan screenshots:
https://monosnap.com/file/r9n1EAuKBsg4MQC10R8xMn4z...
https://monosnap.com/file/VS8qVtI3DoSWqaCCdIp53Ixf...
Tell me how to send data correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kudis, 2018-06-22
@kudis

Your code will work fine on 99.9% of servers, but apparently due to the peculiarities of this service, or rather the processing of requests on it, it is not applicable for a specific task.
I can suggest a CURL solution:

$key = 'ТУТ МОЙ КЛЮЧ ОТ АПИ https://tinypng.com/developers';
$serviceUrl = 'https://api.tinify.com/shrink';
$imgUrl = 'https://tinypng.com/images/panda-happy.png';

$headers = [
    'Content-Type: application/json',
    'Accept: */*',
    'Authorization: Basic ' . base64_encode('api:' . $key)
];

$arData = [
    'source' => [
        'url' =>  $imgUrl
    ]
];

$myCurl = curl_init();
curl_setopt_array($myCurl, [
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $serviceUrl,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($arData)
]);

$response = curl_exec($myCurl);

curl_close($myCurl);

var_dump($response);

A
AndreyVSmirnov, 2021-08-03
@AndreyVSmirnov

Most likely the problem is in mbstring.func_overload.
It is necessary to perform a system check and fix any errors found.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question