发布请求在邮递员中有效,但在php中不起作用

时间:2020-04-13 20:55:43

标签: php curl post http-post postman

这些是邮递员中的参数:

POST URL:

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

标题:

apikey: 6277FF29BB19666078AC
content-type: application/json

正文:(在下一个示例中,用户名和密码不正确)

{“用户名”:“ xxx@xxx.com”,“密码”:“ xxx”,“语言环境”:“ 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中的工作方式非常奇怪,有帮助吗?

1 个答案:

答案 0 :(得分:1)

尝试将“ Content-Length”添加到CURLOPT_HTTPHEADER:

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

您需要json的字符串长度。