我试图调用一个基于Java的服务,该服务使用来自PHP(Magento)应用程序的Jackson对象映射器。在这两个我发送相同的头和相同的参数,但CURL调用工作得很好,因为PHP调用失败与以下消息,
'No content to map to Object due to end of input'
My curl如下,
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/
PHP请求的代码如下,
$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();
我不是使用jackson对象映射器的java服务的所有者,所以我不知道在另一边发生了什么
任何关于调试或修复此问题的建议将不胜感激
终于成功了。问题是错误的实现在我的代码结束,如果你参考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();
这就解决了问题。我不确定是否有更好的方法,但如果有更好的方法,我很乐意使用。