如何在CakePHP中发送JSON POST请求

6
我需要准确地发送以下内容:
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的方法。

希望你们可以给我一个示例,谢谢!

2个回答

23

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

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

如果您有任何问题,请让我知道,我很乐意帮助您;)


-1
如果你想在PHP中实现这个功能,我建议使用curl。以下代码未经测试,所以不能保证它是正确的:
$json = array(
    'api_key' => 'My_API_KEY',
    'user_id' => 'MY_UNIQUE_USER_ID',
    'traits' => array(
          'email' =< 'dhruv@outbound.io',
          'name' => 'Dhrub Mehta',
          'phone' => '650xxxyyyyy'
     )
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, 'http://api.outbound.io/api/v1/identify');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));
curl_setopt($ch, CURLOPT_POST, 1);

$results = curl_exec($ch);
if (curl_errno($ch)) {
    debug(curl_error($ch));
} else {
    curl_close($ch);
}

return $results;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接