简体   繁体   中英

post request works in postman but not in php

Those are the parameters in the postman:

POST URL:

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

Headers:

apikey: 6277FF29BB19666078AC
content-type: application/json

body: (username and pass are incorrect in the next example)

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

and as a result, I received a JSON page that confirms that I logged on in the website.

But when i conver this code into 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;

And this is not working when I start the script I received this error:

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

Very strange how this cna work in the postman and not in the PHP, any help?

Try to add "Content-Length" to CURLOPT_HTTPHEADER:

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

You need string length of you json.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM