如何在php-Codeigniter中向REST服务器api发送帖子请求?

时间:2014-12-12 09:07:43

标签: php json codeigniter rest rest-client

我一直在尝试在我的CodeIgniter RestClient控制器中发出一个POST请求,以便在我的RestServer中插入数据,但好像我的POST请求错了。

这是我在控制器中的RestClient POST请求:

$method = 'post';
$params = array('patient_id'      => '1',
                'department_name' => 'a',
                'patient_type'    => 'b');
$uri = 'patient/visit';
$this->rest->format('application/json');
$result = $this->rest->{$method}($uri, $params);

这是我的RestServer的控制器:患者

function visit_post()
{
    $insertdata=array('patient_id'      => $this->post('patient_id'),
                      'department_name' => $this->post('department_name'),
                      'patient_type'    => $this->post('patient_type') );

    $result = $this->user_model->insertVisit($insertdata);

    if($result === FALSE)
    {
        $this->response(array('status' => 'failed'));
    }
    else
    {
        $this->response(array('status' => 'success'));
    }
}

这是 user_model

public function insertVisit($insertdata)
{
   $this->db->insert('visit',$insertdata);
}

2 个答案:

答案 0 :(得分:9)

最后我提出了一个解决方案,我使用PHP cURL向我的REST服务器发送一个帖子请求。

这是我的RESTclient POST请求

 $data = array(
            'patient_id'      => '1',
            'department_name' => 'a',
            'patient_type'    => 'b'
    );

    $data_string = json_encode($data);

    $curl = curl_init('http://localhost/patient-portal/api/patient/visit');

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
    );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // Make it so the data coming back is put into a string
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);  // Insert the data

    // Send the request
    $result = curl_exec($curl);

    // Free up the resources $curl is using
    curl_close($curl);

    echo $result;

答案 1 :(得分:0)

你可以调试你的代码。尝试打印全局变量$ _POST。 我认为这可以解决你的问题 只需使用$this->input->post代替  而不是$this->post