2014-08-27 123 views
2

我試圖用發送JSON對象作爲POST命令如下:使用一個Zend_Http_Client發送JSON POST

$uri = "http://amore-luce.com/product_create"; 
    $product = $observer->getEvent()->getProduct(); 
    $json = Mage::helper('core')->jsonEncode($product); 
    Mage::log(" Json={$json}", null,'product-updates.txt'); 

    // new HTTP request to some HTTP address 
    $client = new Zend_Http_Client('http://amore-luce.com/product_create'); 
    // set some parameters 
    $client->setParameterPost('product', $json); 
    // POST request 
    $response = $client->request(Zend_Http_Client::POST); 

當我查看$ JSON數據是存在的,一切看起來不錯 - 但是POST不發送json數據。我用一個簡單的電子郵件形式應該發送我的反應捕捉它:

<?php   
    $webhookContent = ""; 
    $ref = "";  
    $webhook = fopen('php://input' , 'rb'); 
    while (!feof($webhook)) { 
     $webhookContent .= fread($webhook, 4096); 
    } 
    fclose($webhook); 

    $headers = array(); 
     foreach($_SERVER as $key => $value) { 
      if (substr($key, 0, 5) <> 'HTTP_') { 
       continue; 
      } 
      $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5))))); 
      $headers[$header] = $value; 
     } 

    foreach ($headers as $header => $value) { 
     $ref .= "$header: $value <br />\n"; 
    } 

    $post = file_get_contents('php://input'); 
    $to = "[email protected]"; //the address the email is being sent to 
    $subject = "This is the subject"; //the subject of the message 
    $msg = "This is the message - Webhook content: ".$webhookContent." This is url: ".$ref; //the message of the email 

    mail($to, $subject, $msg, 'From: PHP Scriptv2 <[email protected]>'); //send the email. 

    echo ($_SERVER['HTTP_REFERER']."<br>".$_SERVER['REQUEST_URI']); 
    ?> 

本頁面可與我已經發送給它的其他JSON POST請求。我在發送POST請求方面相當新,所以任何幫助將不勝感激。

回答

4

嘗試改變:

$client->setParameterPost('product', $json); 

到:

$client->setHeaders('Content-type','application/json'); 
$client->setParameterPost('product', $json); 

或使用:

​​
+0

使用$客戶 - > setRawData($ JSON,「應用/ JSON」);失敗。但是,使用上面的兩條線是一種享受。謝謝! – 2014-08-27 23:54:02

1

所以更新/更改答案我是如何做的到這些代碼:

$uri = "http://requestb.in/p6p4syp6"; 
    $product = $observer->getEvent()->getProduct(); 
    $json = Mage::helper('core')->jsonEncode($product); 
    Mage::log(" Json={$json}", null,'product-updates.txt'); 

    $client = new Zend_Http_Client($uri); 
    $client->setRawData($json, null)->request('POST'); 

更改SetRawData($ json,null)是這個位 - 使用SetRawDate($ json,'application/json')導致它失敗。

感謝Voodoo417 - 我也來試試你的建議,看看,讓我設置了正確的類型