Олег Сафин Олег Сафин - 6 months ago 22
PHP Question

301 status while using post request

I'm sending POST request, containing JSON data. My PHP code returns a 301 status. I tried to do this in JS and C# but it is still not working. BUT!! using Postman I receive the correct answer with the data I need. Still, I'm copy-pasting code generated by Postman and it isn't working either!!

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-dev.gu.spb.ru/hakatonRest/checkInn",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n\"serviceCode\":\"FNS001\",\r\n\"serviceData\": {\r\n \"firstName\":\"иван\",\r\n \"lastName\":\"иванов \",\r\n \"secondName\":\"иванович\",\r\n \"birthday\":\"22.07.1989\",\r\n \"documentType\":\"21\",\r\n \"documentSeries\":\"4112\",\r\n \"documentNumber\":\"412512\"\r\n}\r\n\r\n}\r\n",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
"postman-token: 1dcb6bfa-531c-aff8-535e-70ba5c799775"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Answer

Add CURLOPT_FOLLOWLOCATION to follow the redirections.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Secondly your CURLOPT_POSTFIELDS => "{\r\n\"serviceCode\":\"FNS00 seems incorrect json data string (json do not contain \r\n in there). Please validate json data before passing here.