json - 如何在cakephp中发送json帖子

标签 json api cakephp post outbound

我需要发送这个:

POST http://api.outbound.io/api/v1/identify
Content-Type: application/json
{
 "api_key": "MY_API_KEY",
 "user_id": "MY_UNIQUE_USER_ID",
 "traits" : {
    "email" : "dhruv@outbound.io",
    "name" : "Dhruv Mehta",
    "phone" : "650xxxyyyyy"
 }
}

我从来没有做过这样的事情,我做了很多研究,但我找不到如何将这些参数发送到该 URL

我希望你们能帮我举个例子,祝好!

最佳答案

经过大量研究,我找到了如何做到这一点......

1.- 使用

App::uses('HttpSocket', 'Network/Http'); // you should put this on your controller

2.- 这在你的函数中

$HttpSocket = new HttpSocket(); 

3.- 这是您想要通过 POST 发送的数据(在本例中,我将使用我使用过的变量..您可以替换它们,添加更多或删除一些..这取决于您想要的信息发送)

$data = array(
           "api_key" => "API KEY",
           "user_id" => $idUser,
           "event" => "other",
           "extra" => array(
                          "course" => $course,
                          "price"=> $price )
               );

3.- 您设置标题

$request = array(
        'header' => array('Content-Type' => 'application/json',
        ),
    );

4.-json_encode 它

 $data = json_encode($data);

5.- 您要将帖子发送到哪里?,哪些数据?,请求类型?,这样做

$response = $HttpSocket->post('http://api.yourweburl.com/api/', $data, $request);

*.- 您可以看到取消注释此代码段的响应

//pr($response->body());

*.- 最后,如果你想在一切完成后重定向到某个地方..这样做......

$this->redirect(array('action' => 'index'));

你应该有这样的东西。

public function actiontooutbound($idUser, $course, $price){
 $HttpSocket = new HttpSocket();

    $data = array(
           "api_key" => "API KEY",
           "user_id" => $idUser,
           "event" => "other",
           "extra" => array(
                          "course" => $course,
                          "price"=> $price )
               );

    $request = array(
        'header' => array(
            'Content-Type' => 'application/json',
        ),
    );
    $data = json_encode($data);
    $response = $HttpSocket->post('http://api.outbound.io/api/v1/track', $data, $request);
   // pr($data);
    //pr($response->body());
   $this->redirect(array('action' => 'index'));     

}

这是从另一个函数调用此函数的方式(以防万一)

$this->actiontooutbound($idUser, $course, $price); 

如果您有任何疑问,请立即告诉我,我很乐意为您提供帮助;)

关于json - 如何在cakephp中发送json帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031901/

相关文章:

json - 如何从 Jenkins 构建请求中获取 JSON 对象

python - 解析 JSON 对象时,保留字作为数据类中的属性名称

vb.net - 通过 VB 中的 API 实现 LINQ 表达式到表达式树

java - 在 Java 中,我如何设计一个既通用、简单又可读的 API

json - 如何在不默认为 float64 的情况下解码各种类型的列表

javascript - 访问消息正文中的 Json 字段

c++ - 在接口(interface)中使用通用指针的原因/正确情况是什么

php - 使用 WordPress 开发 Web 应用程序

php - SQLSTATE[HY000] [1045] 使用 CakePHP 拒绝用户 'username' @'localhost' 的访问

php - 在 AppModel->afterFind (cakePHP) 中转换时区之间的日期