2

I am trying to call a Java based service that uses a Jackson object mapper from a PHP(Magento) application. In both of them I am sending the same headers and same parameters, but the CURL call works fine where as PHP call fails with following message,

'No content to map to Object due to end of input'

My curl is as follows,

curl -v -k -X POST -H "Content-Type:application/json;charset=UTF-8" -d '{"name":"john","email":"john@doe.com"}' https://localhost:8080/webapps/api/

The PHP Request is code is as follows,

                 $iClient = new Varien_Http_Client();
                 $iClient->setUri('https://localhost:8080/webapps/api/')
        ->setMethod('POST')
        ->setConfig(array(
                'maxredirects'=>0,
                'timeout'=>30,
        ));
    $iClient->setHeaders($headers);
    $iClient->setParameterPost(json_encode(array(
                    "name"=>"John",
                    "email"=>"john@doe.com"
                    )));    
    $response = $iClient->request();

I am not the owner of the java service that uses jackson object mapper so I have no idea what happens on other side

Any suggestions on debugging or fixing this would be appreciated

4

1 回答 1

0

好吧,这终于奏效了。如果您参考Zend_Http_Client. 请参考以下来自 Zend_Http_Client 的方法,

/**
 * Set a POST parameter for the request. Wrapper around _setParameter
 *
 * @param string|array $name
 * @param string $value
 * @return Zend_Http_Client
 */
public function setParameterPost($name, $value = null)
{
    if (is_array($name)) {
        foreach ($name as $k => $v)
            $this->_setParameter('POST', $k, $v);
    } else {
        $this->_setParameter('POST', $name, $value);
    }

    return $this;
}

/**
 * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
 *
 * @param string $type GET or POST
 * @param string $name
 * @param string $value
 * @return null
 */
protected function _setParameter($type, $name, $value)
{
    $parray = array();
    $type = strtolower($type);
    switch ($type) {
        case 'get':
            $parray = &$this->paramsGet;
            break;
        case 'post':
            $parray = &$this->paramsPost;
            break;
    }

    if ($value === null) {
        if (isset($parray[$name])) unset($parray[$name]);
    } else {
        $parray[$name] = $value;
    }
}

所以 setParameterPost 以某种方式只尊重数组参数(键值对),而我的 POST 有效负载是一个 json 字符串。所以为了解决这个问题,我修改了如下代码,

$iClient = new Varien_Http_Client();
             $iClient->setUri('https://localhost:8080/webapps/api/')
    ->setMethod('POST')
    ->setConfig(array(
            'maxredirects'=>0,
            'timeout'=>30,
    ));
$iClient->setHeaders($headers);
$iClient->setRawData(json_encode(array(
                "name"=>"John",
                "email"=>"john@doe.com"
                )), "application/json;charset=UTF-8");    
$response = $iClient->request();

这解决了这个问题。我不确定更好的方法,但如果有更好的方法,我会很高兴使用它。

于 2013-03-04T09:13:58.003 回答