Zend_HTTP_Client wont let me POST any data

痞子三分冷 提交于 2019-12-04 07:26:36

Here is what you are missing:

$json = json_encode($data);
$client->setRawData($json, 'application/json')->request('POST');

sends a POST request but the data in the POST body is not a url-encoded string, instead it is just raw JSON.

Calling $this->getRequest()->getParam('foo') looks at the PHP superglobals $_GET and $_POST which will not contain any of the JSON parameters. The reason it will be empty is because PHP couldn't parse the POST data since it was JSON and not HTTP url-encoded content.

The solution is to use something like this in the dataAction if you want to receive JSON data in the POST body.

$post = $this->getRequest()->getRawBody();

try {
    $json = Zend_Json::decode($post);

    // now access parameters from $json array
} catch (Zend_Json_Exception $ex) {
    echo "Failed to decode request, POST did not contain valid JSON.";
}

Edit: Here is the full code you can mess with.

public function requestAction()
{
    // CHANGE THIS
    $uri = 'http://playground/zendapp/public/index/data';

    $config = array(
            'adapter'   => 'Zend_Http_Client_Adapter_Curl',
            'curloptions' => array(CURLOPT_FOLLOWLOCATION => true),
    );
    $client = new Zend_Http_Client($uri, $config);

    $data = array(
            'userID'      => 'TEST TEST',
            'value'       => 1,
            'description' => 'ABCDEFG',
    );

    $json = json_encode($data);

    $resp = $client->setRawData($json, 'application/json')->request('POST');

    var_dump($resp->getBody());

    exit();

}

public function dataAction()
{
    $post = $this->getRequest()->getRawBody();

    try {
        $json = Zend_Json::decode($post);

        print_r($json);
    } catch (Exception $ex) {
        echo "failed to decode json";
    }

    exit;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!