php - 如何在 php-Codeigniter 中向 RESTserver api 发送发布请求?

标签 php json codeigniter rest rest-client

我一直在尝试在我的 CodeIgniter RestClient Controller 中发出 POST 请求以将数据插入我的 RestServer,但我的 POST 请求似乎是错误的。

这是我在 Controller 中的 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 的 Controller :patient

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

最佳答案

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

这是我的 REST 客户端 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;

关于php - 如何在 php-Codeigniter 中向 RESTserver api 发送发布请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27440171/

相关文章:

php - 如何使用 DOMPDF 下载 pdf 格式的完整 HTML 页面?

PHP根据文件夹结构动态生成命名空间

json - Mongoose - 无法检索快速 route 的虚拟字段

javascript - 处理从 javascript 对象获取的数据

php - 在 Codeigniter View 中加载数据

php - CodeIgniter 嵌套 where 条件

php - 检查 PHP 上的 Mysql 数据库中是否存在值

php - 使用 empty() 函数检查对象是否为 null 是否正确?

javascript - JSON 菜单按字母顺序排列

jQuery 自动完成与 Codeigniter,不在索引函数之外工作