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

时间:2012-11-14 09:45:23

标签: php json curl

我在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。

任何想法我做错了什么?

5 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

你能否在接收端看到你的args是什么样的?

到了Rookies的回答 - 这可能与你如何通过你的后场有关吗?通常,postfield参数将期望键值数组或urlencoded字符串(key1 = val1&amp;)。没有你的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...
祝你好运。

答案 2 :(得分:0)

我知道问题是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/

答案 3 :(得分: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;
}

答案 4 :(得分:-1)

CURLOPT_POSTFIELDS:必须这样“a = 1111&amp; 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;
        }
?>