简体   繁体   English

PHP:如何使用GET发送cURL请求?

[英]PHP: How to send cURL request using GET?

I am using cURL for an API call, below is my code:我正在使用 cURL 进行 API 通话,下面是我的代码:

$data = array(
            'r'                          =>  'create',
            '_object'                    =>  'Question',
            '_api_key'                   =>  '........',
            '_user_id'                   =>  $creator_id,
            '_subtype_id'                =>  $type_id,
            '_subtopic_id'               =>  $subtopic_id,
            '_title'                     =>  $title,
            '_description'               =>  $description,             
            '_encoded_xml'               =>  $main_xml
        );
     
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"http://urlhere/v1/resources/objects");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        $server_output = curl_exec($ch);    
        curl_close ($ch);
        print_r($server_output);

I want these parameters to be sent as GET request instead of POST , how can I do that pls advise我希望这些参数作为GET请求而不是POST发送,我该怎么做请告知

CURLOPT_POSTFIELDS is for the body (payload) of a POST request. CURLOPT_POSTFIELDS用于POST请求的主体(有效负载)。 For GET requests, the payload is part of the URL.对于GET请求,有效负载是 URL 的一部分。

You just need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.你只需要构造URL和你需要发送的arguments(如果有的话),去掉其他选项到cURL。


$data = array(
            'r'                          =>  'create',
            '_object'                    =>  'Question',
            '_api_key'                   =>  '........',
            '_user_id'                   =>  $creator_id,
            '_subtype_id'                =>  $type_id,
            '_subtopic_id'               =>  $subtopic_id,
            '_title'                     =>  $title,
            '_description'               =>  $description,             
            '_encoded_xml'               =>  $main_xml
        );


        $send_data = http_build_query($data);
     
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,"http://urlhere/v1/resources/objects?" . $send_data);
        // curl_setopt($ch, CURLOPT_POST, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        
        $server_output = curl_exec($ch);    
        curl_close ($ch);
        print_r($server_output);

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

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