2014-08-27 121 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 - 我也来试试你的建议,看看,让我设置了正确的类型