2014-01-09 40 views
4

我需要發送正是這一點:如何發送CakePHP中JSON後

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" : "[email protected]", 
    "name" : "Dhruv Mehta", 
    "phone" : "650xxxyyyyy" 
} 
} 

我從來沒有這樣的事情,我已經做了很多的研究,但我怎麼也找不到發送這些參數到那個URL

我希望你們可以幫我舉個例子,最好的問候!

回答

19

了大量的研究後,我發現怎麼辦呢?

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中這樣做,我會使用捲曲。以下是未經測試,所以不能保證它是正確的:

$json = array(
    'api_key' => 'My_API_KEY', 
    'user_id' => 'MY_UNIQUE_USER_ID', 
    'traits' => array(
      'email' =< '[email protected]', 
      '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;