我试图使用原生的Zend Framework 2 http \ curl库,我可以让它将请求发送到远程应用程序我只是无法将它传递给POST值。
这是我的代码,显示了2个示例,第一个是使用本机PHP curl,它工作正常,第二个是使用ZF2 http \ curl库,它不传递任何POST参数。
示例1(本机PHP库)
$url = $postUrl . "" . $postUri;
$postString = "username={$username}&password={$password}";
//This works correctly using hte native PHP sessions
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
curl_close($ch);
var_dump($output); //outputs the correct response from the remote application
示例2(ZF2库使用)
$url = $postUrl . "" . $postUri;
$postString = "username={$username}&password={$password}";
//Does not work using ZF2 method!
$request = new Request;
$request->setUri($url);
$request->setMethod('POST');
$adapter = new Curl;
$adapter->setOptions([
'curloptions' => [
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postString,
CURLOPT_HEADER => 1
]
]);
$client = new Client;
$client->setAdapter($adapter);
$response = $client->dispatch($request);
var_dump($response->getBody());
是否有人能够指出我在哪里出错了?我查看了ZF2文档,但它们并不是最全面的。
答案 0 :(得分:6)
您并不需要在Curl
适配器上指定所有这些详细信息。这是ZF2为您所做的事情:
$url = $postUrl . $postUri;
$postString = "username={$username}&password={$password}";
$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->setContent($postString);
$response = $client->dispatch($request);
var_dump($response->getContent());
答案 1 :(得分:6)
这是我用来解决这个问题的解决方案。
$url = $postUrl . "" . $postUri;
$request = new Request;
$request->getHeaders()->addHeaders([
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
]);
$request->setUri($url);
$request->setMethod('POST'); //uncomment this if the POST is used
$request->getPost()->set('username', $username);
$request->getPost()->set('password', $password);
$client = new Client;
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$response = $client->dispatch($request);