我正在尝试使用Zend2向端点发出POST请求。
我可以使用Curl在PHP中发布帖子,但无法使用Zend2客户端和请求重现该Curl请求。
例如,以下工作正常。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
$postfields = array();
$postfields['CostCode'] = '999999801';
curl_setopt($ch, CURLOPT_POSTFIELDS,
$postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data;
charset=UTF-8',
'Connection: Keep-Alive'
));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
结果返回: -
<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse">
<Result>1</Result></ValidateCCResult>
表明成本代码有效。
但是,当我尝试在Zend中重现它时,我没有得到我期望的响应。
$postfields = array();
$postfields['CostCode'] = '999999801';
$client = new \Zend\Http\Client();
$client->setAdapter(new \Zend\Http\Client\Adapter\Curl());
$request = new \Zend\Http\Request();
$request->setUri($url);
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getHeaders()->addHeaders([
'Content-Type' => 'multipart/form-data; charset=UTF-8'
]);
$request->setContent($postfields);
$response = $client->dispatch($request);
<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse"><Result>0</Result>
<Message/></ValidateCCResult>
我尝试了不同的内容类型,但感觉这与setContent更改$ postfields数组有关。
答案 0 :(得分:1)
尝试使用
$postfields['CostCode'] = '999999801';
$uri = 'http://localhost';
$client = new \Zend\Http\Client();
$client->setUri($uri);
$client->setMethod('POST');
$client->setOptions(array(
'keepalive' => true,
));
$client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
$client->setParameterPost($postfields);
$response = $client->send();
echo $response->getBody();