post 请求在 postman 中有效但在 php 中无效

post request works in postman but not in php

那些是邮递员中的参数:

POST URL:

https://rest-api.wm.com/user/authenticate

Headers:

apikey: 6277FF29BB19666078AC
content-type: application/json

body:(下例中用户名和密码不正确)

{"username":"xxx@xxx.com","password":"xxx","locale":"en_US"}

因此,我收到了一个 JSON 页面,确认我已登录该网站。

但是当我将这段代码转换成 PHP

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://rest-api.wm.com/user/authenticate",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>"{\"username\":\"xxx@xxx.com\",\"password\":\"xxx\",\"locale\":\"en_US\"}",
  CURLOPT_HTTPHEADER => array(
    "apikey:  6277FF29BB19666078AC",
    "content-type:  application/json",
    "Content-Type: text/plain"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

当我启动脚本时这不起作用我收到此错误:

{"status":"failed","errorMsg":"Please enter valid input","statusCode":400}

很奇怪这个 cna 如何在邮递员中工作而不是在 PHP 中工作,有帮助吗?

尝试将 "Content-Length" 添加到 CURLOPT_HTTPHEADER:

CURLOPT_HTTPHEADER => array(
      "apikey:  6277FF29BB19666078AC",
      "Content-Type: application/json",
      "Content-Length: " . strlen($json))
 ),

您需要 json 的字符串长度。