首页 > 解决方案 > 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这样的请求正在工作

标签: phphttpcurlpostmanguzzle

解决方案


您的代码有两个问题,首先该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);
?>

);


推荐阅读