PHP CURL给我401错误,但在POSTMAN上工作正常

时间:2018-08-05 12:27:10

标签: php curl

我正在调用两个API,一个登录名,第二个用于添加用户。要首先添加用户,我需要调用登录API,然后添加用户API。当我在邮递员中测试这些API时,它工作正常,但是当我使用CURL调用添加用户时,却收到401错误。

PostMan中的登录API Login API

在POSTMAN中添加用户API User API

可以正常运行的登录API PHP代码

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://example.com/sapi/login?action=login",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "login=login&password=password",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded"

  ),
));

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

curl_close($curl);

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

但是当我使用以下代码调用添加用户api时,会给我错误。

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://example.com/sapi/profile/generic?action=add",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => 
    '{"data":{"user":{"generic":{"userid":"Hagrid","password":"abc123","firstname":"afds","lastname":"asf","useremail":"test@gmail.com"}}}}',
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/json"

  ),
));

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

curl_close($curl);

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

1 个答案:

答案 0 :(得分:0)

在curl_exec之前添加以下代码

curl_setopt($curl, CURLOPT_COOKIEJAR, "COOKIE.txt");
curl_setopt($curl, CURLOPT_COOKIEFILE, "COOKIE.txt");