简体   繁体   中英

send json string in post request and get the header response

I'm trying to send json object to server and to get variable from the header of response. when I tried to do this request using postman, it's work great. but in PHP I get errors.

在此处输入图片说明

my php code:

$url = 'https://test.com/login';
$postArray = array('email' => 'test@gmail.com', 'password' => 'test');  

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postArray));
$response = curl_exec ($curl);

$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

var_dump($header);

but the response of header I get in php:

string(370) "HTTP/1.1 500 Internal Server Error Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Type: application/json;charset=UTF-8 Date: Wed, 13 Dec 2017 09:48:26 GMT Expires: 0 Pragma: no-cache Server: nginx/1.10.1 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Content-Length: 320 Connection: keep-alive "

how to fix the code to make it work? thank you very much.

update: I add to code:

curl_setopt($curl, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

and the problem solved. thank you

由于内容是json,因此您需要使用multipart/form-data

curl_setopt($curl, CURLOPT_HTTPHEADER, array("content-type: multipart/form-data;"))

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