【问题标题】:JSON raw POST cURL request not workingJSON原始POST cURL请求不起作用
【发布时间】:2019-01-19 09:45:09
【问题描述】:

非常感谢任何帮助,在此先感谢。

我的 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 这样的请求正在工作

【问题讨论】:

    标签: php http curl postman guzzle


    【解决方案1】:

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

    );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多