使用PHP cURL发布JSON并显示JSON响应

hlswsv35  于 2022-11-13  发布在  PHP
关注(0)|答案(5)|浏览(214)

我已经在Stack Overflow上找了很多答案,但就是找不到。

<?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。
你知道我哪里做错了吗

deikduxw

deikduxw1#

尝试使用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;
uxh89sit

uxh89sit2#

您是否能够看到接收端的参数是什么样子的?
对于新手的回答--它是否与您传递postfield的方式有关?通常postfield参数需要key值数组或urlencoded字符串(key 1 = val 1 &)。如果没有JSON($data_string)“value”的“key”,服务器是否知道如何接受postfield?您可以尝试以下方法吗?

// 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...

祝你好运

x8goxv8g

x8goxv8g3#

我知道这个问题已经2年了,但它仍然得到了很多意见。
这看起来像是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/

j5fpnvbx

j5fpnvbx4#

尝试此功能

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;
}
kiayqfof

kiayqfof5#

曲线后字段:必须像这样“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;
        }
?>

相关问题