使用 PHP cURL POST JSON 并显示 JSON 响应

问题描述 投票:0回答:5

我在 Stack Overflow 上查了很多资料,试图找到问题的答案,但就是找不到。我正在尝试发布以下 JSON

<?php

$data_string = '{
        "jsonrpc": "2.0",
        "method": "login",
        "id": 1,
        "params": {
          "params": {
            "username": "4321",
            "password":  "1234"
          }
        }
      }';

$ch = curl_init('https://domain.com');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$result = curl_exec($ch);

echo $result;
?>

我没有得到任何回应,尽管它与 jQuery 和 AJAX 配合得很好。我查看Chrome的开发者工具,方法是GET,这很奇怪,因为我在代码中将其设置为POST。

有什么想法我做错了吗?

php json curl
5个回答
0
投票

尝试使用 JSON 字符串作为请求正文发出 GET 请求:

$data_string = '{
        "jsonrpc": "2.0",
        "method": "login",
        "id": 1,
        "params": {
          "params": {
            "username": "4321",
            "password":  "1234"
          }
        }
      }';

$ch = curl_init('https://domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
'Content-Type: application/json',                                                                                
'Content-Length: ' . strlen($data_string))                                                                       
);  
curl_setopt($ch, CURLOPT_POSTFIELDS,   $data_string );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  'GET');

$result = curl_exec($ch);
echo $result;

0
投票

你能看到你的参数在接收端是什么样子吗?

就新秀的回答而言——这可能与你通过后场的方式有关吗?通常,postfield 参数需要键值数组或 urlencoded 字符串 (key1=val1&)。如果没有 JSON ($data_string)“值”的“键”,服务器是否知道如何接受 postfields?您可以尝试以下方法吗?

// Personal preference here - arrays are easier for me to read
// Create a multi dem array dictionary with your values
$_dictionary = array("jsonrpc"=>"2.0",
                     "method" =>"login",
                     "id"     =>1,
                     "params" =>array("params"=>array("username"=>"4321","password"=>"1234"))
                    );

// json_encode 
$_dictionary = json_encode($_dictionary);

// your $data_string variable will now be in key=value  
$data_string = "mydata={$_dictionary}";

// set $data_string to your CURLOPT_POSTFIELDS...

祝你好运。


0
投票

我知道这个问题已经有两年了,但仍然有很多人浏览。

这看起来像是 SSL 问题。你可以尝试:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

有关更多信息,请阅读:http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/


0
投票

试试这个功能

function request($url, $data, $method = "POST", $json = true) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
    if ($json) {
        $data_value = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: '.strlen($data_value)));
    } else $data_value = http_build_query($data);

    switch ($method) {
        case "POST":
            if ($json) curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            else curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data_value);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            $url = sprintf("%s?%s", $url, $data_value);
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($curl);
    if ($result == false) throw new Exception(curl_error($curl));
    curl_close($curl);


    return $result;
}

-1
投票

CURLOPT_POSTFIELDS:必须喜欢这个“a=1111&b=2222”

example 1:
<?php
$useragent = 'PHP Client 1.0 (curl) ' . phpversion();
$post_string="a=1&b=1";
$url_with_get="http://xxx.xxx.com";
$result = @exec("curl -s --connect-timeout 10 --user-agent \"$useragent\" -d\"$post_string\" \"$url_with_get\"");
var_dump($result);
?>

example 2:
<?php
$useragent = 'PHP Client 1.0 (curl) ' . phpversion();
$post_string="a=1&b=1";
$url_with_get="http://xxx.xxx.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_with_get);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
curl_close($ch);

var_dump($result);
?>

example 3:
<?php
$content_type = 'application/x-www-form-urlencoded';
$content = "a=1&b=1";
$server_addr = "http://xxx.xxx.com";
var_dump(http_post($content_type, $content, $server_addr));

function http_post($content_type, $content, $server_addr) {

                $user_agent = 'PHP Client 1.0 (non-curl) ' . phpversion();
                $content_length = strlen($content);
                $context = array(
                        'http' => array(
                                        'method' => 'POST',
                                        'user_agent' => $user_agent,
                                        'header' => 'Content-Type: ' . $content_type . "\r\n" .
                                        'Content-Length: ' . $content_length,
                                        'content' => $content,
                                        'timeout' => 10,
                                )
                );
                $context_id = stream_context_create($context);
                $sock = fopen($server_addr, 'r', false, $context_id);

                $result = '';
                if ($sock) {
                        while (!feof($sock)) {
                                $result .= fgets($sock, 4096);
                        }
                        fclose($sock);
                }
                return $result;
        }
?>
© www.soinside.com 2019 - 2024. All rights reserved.