如何在codeigniter的rest api中访问curl post数据?

问题描述 投票:-1回答:1

我想把Codeigniter控制器中的数据用curl发布到API中,但无法访问API中的数据,以下是我的CURL代码.......

     class SearchJobs extends CI_Controller {


public function index()
{   
    $headers = array(

        'Content-Type:application/json'

    );

    $fields=$this->input->post();
    /////////////////////get jobs/////////////////

    $api_path=API_PATH."index.php/searchJobs/getJobs";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_path);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
    $featuredJobs = curl_exec($ch);


      if(curl_errno($ch)) {    
          echo 'Curl error: ' . curl_error($ch);  

          exit();  
      } else {    
          // check the HTTP status code of the request
            $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($resultStatus != 200) {
                echo stripslashes($featuredJobs);
                die('Request failed: HTTP status code: ' . $resultStatus);

            }
         $featured_jobs_array=(array)json_decode($featuredJobs);
         print_r($featured_jobs_array);
         exit();
      } 


    $this->load->view('searchjobs/index',array('featuredJobs'=>$featured_jobs_array));
}

}

...

这就是我在API中访问它的方式。

...

 public function getJobs_post()
{   
    $data_array=array();
    $res_array=array();
    $pageNo = $this->input->get('pageNo');

    $where = ' j.isActive="y" and isApproved=1  ';

    $posted_skills=$this->input->get('skills');

    $locations=$this->input->get('location');

...

但是,我可以用同样的方法轻松地从postman访问API中的帖子数据。$this->input->get('skills');.

php rest codeigniter curl codeigniter-3
1个回答
0
投票

删除Json头 $headers = array( 'Content-Type:applicationjson' )。

无需json_encode直接发布数据curl_setopt($ch,CURLOPT_POSTFIELDS, $fields)。

© www.soinside.com 2019 - 2024. All rights reserved.