php - JSON原始POST cURL请求不起作用
问题描述
非常感谢任何帮助,在此先感谢。
我在以下位置托管的 storeCallback.php 文件:http://xxxxx/storeCallback.php
<?php
die(var_dump($_REQUEST));
我正在创建一个 post json 原始请求:
1.
$url = "http://xxxxx/storeCallback.php/storeCallback.php";
$body =['foo' => 'bar'];
$body_string = json_encode($body);
$header = array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: '.strlen($body_string),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body_string);
$json_response = curl_exec($curl);
$response = json_decode($json_response, true);
die(var_dump($response));
2.
$url = "http://xxxxx/storeCallback.php/storeCallback.php";
$body =['foo' => 'bar'];
$body_string = json_encode($body);
$header = array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: '.strlen($body_string),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body_string);
$json_response = curl_exec($curl);
$response = json_decode($json_response, true);
die(var_dump($response));
3.
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('http://xxxxx/storeCallback.php/storeCallback.php', [
GuzzleHttp\RequestOptions::JSON => ['for' => "bar"],
]);
echo $response->getBody()->getContents();
没有任何效果,在所有情况下响应都是 [] (空数组) ,但是发送像http://xxxxx/storeCallback.php/storeCallback.php?foo=bar这样的请求正在工作
解决方案
您的代码有两个问题,首先该storeCallback.php
文件没有提供有效的 JSON 输出,因此当您尝试使用 cURL 检索它时,您无法将其解析为 JSON。
正确的版本如下: storeCallback.php
<?php
die(json_encode($_REQUEST));
?>
此外,您应该按如下方式发出 cURL 请求:
<?php
$url = "http://pc.medimetry.in/storeCallback.php";
$body = ['foo' => 'bar'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$json_response = curl_exec($ch);
curl_close($ch); //important, always close cURL connections.
$parsed_response = json_decode($json_response);
var_dump($parsed_response);
?>
);
推荐阅读
- vaadin - 打印当前页面时如何隐藏项目?
- java - 如何使用变量 INT 打印 DOUBLE
- google-apps-script - MailApp 使用 Gsuite 帐户返回递送失败,但不使用 Gmail
- php - 尝试构建两步登录表单时未定义的索引(PHP)
- google-cloud-storage - 压缩/压缩谷歌云存储上的多个文件,无需下载
- amazon-web-services - 如何在同一子网范围内的 ec2 实例中分配/生成新的 IP 地址?
- jersey-2.0 - jersey 客户端失败,ClientResponse 状态为 400
- sublimetext3 - Sublime Text 3 中的新建筑系统
- javascript - 如果 html 数据为空,我想隐藏 div,如果不是,我想显示。HTML JavaScript
- php - Laravel 属性 [title] 在 Eloquent 构建器实例上不存在