简体   繁体   English

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

[英]POST JSON with PHP cURL and show JSON response

I've looked a lot around on Stack Overflow to find an answer to my issue, but simply can't.我在 Stack Overflow 上看了很多遍,想找到我的问题的答案,但根本找不到。 I'm trying to post the following JSON我正在尝试发布以下 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;
?>

I don't get any response, even though it works fine with jQuery and AJAX.我没有得到任何回应,即使它适用于 jQuery 和 AJAX。 When I check Chrome's developer tools, the method is GET, which is weird as I set it to POST in the code.当我查看 Chrome 的开发者工具时,方法是 GET,这很奇怪,因为我在代码中将其设置为 POST。

Any ideas what I'm doing wrong?任何想法我做错了什么?

Try to make GET request with your JSON string as request body:尝试使用您的 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;

Have you been able to see what your args look like on the receiving end?您是否能够在接收端看到您的 args 的样子?

To the point of Rookies answer - could it have something to do with how you're passing your postfields?就 Rookies 的回答而言——这可能与您通过邮递区的方式有关吗? Generally the postfield param will expect key value arrays or urlencoded strings (key1=val1&).通常 postfield 参数将期望键值数组或 urlencoded 字符串 (key1=val1&)。 Without a "key" to your JSON ($data_string) "value" does the server know how to accept the postfields?如果没有 JSON ($data_string) “值”的“键”,服务器是否知道如何接受后字段? Could you maybe try the following?您可以尝试以下方法吗?

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

Good luck.祝你好运。

I know the question is 2 years old but its still getting a lot of views.我知道这个问题已经有 2 年历史了,但它仍然有很多观点。

This looks like a SSL problem.这看起来像一个 SSL 问题。 You could try:你可以试试:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

for more info read this: http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/欲了解更多信息,请阅读: http ://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

Try this function试试这个功能

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

CURLOPT_POSTFIELDS: must like this "a=1111&b=2222" 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;
        }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM