【问题标题】:send json string in post request and get the header response在 post 请求中发送 json 字符串并获取标头响应
【发布时间】:2018-05-27 04:04:42
【问题描述】:

我正在尝试将 json 对象发送到服务器并从响应的标头中获取变量。当我尝试使用邮递员执行此请求时,效果很好。但在 PHP 中出现错误。

我的php代码:

$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);

但是我在 php 中得到的 header 的响应:

string(370) "HTTP/1.1 500 内部服务器错误缓存控制: no-cache, no-store, max-age=0, must-revalidate Content-Type: application/json;charset=UTF-8 日期:2017 年 12 月 13 日星期三 09:48:26 GMT 过期:0 编译指示:无缓存服务器:nginx/1.10.1 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-防护:1;模式=块内容长度:320 连接: 保持活力"

如何修复代码以使其正常工作? 非常感谢。

更新: 我添加到代码中:

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

问题解决了。 谢谢

【问题讨论】:

  • 从您的 PHP 错误日志开始。
  • @marekful 日志中没有错误,因为 php 工作得很好。请求发送成功并得到响应。但是为什么要让请求像邮递员一样工作呢?
  • PHP 在您从 Postman 发送时效果很好,但在发送此 cURL 请求时效果不佳。在后一种情况下,它会生成一个很可能已记录的服务器错误。请...
  • @marekful 哦,我明白你的意思。但是收到我请求的服务器不是我的,所以我无法访问他的错误日志...
  • 然后在您自己的服务器上设置一个脚本来记录请求标头和正文,并比较您为邮递员和您的 curl 请求获得的内容。使用邮递员,您将数据作为“原始”发送,而 cURL 可能会自动添加Content-Type: application/x-www-form-urlencoded 或某事。像这样。

标签: php curl


【解决方案1】:

由于内容是json,所以需要使用multipart/form-data

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

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 2019-02-06
    • 2016-03-28
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多