Mik*_*e B 2 php zend-framework2
我试图使用本机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
Run Code Online (Sandbox Code Playgroud)
示例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());
Run Code Online (Sandbox Code Playgroud)
有人能够指出我在哪里出错吗?我查看了ZF2文档,但它们并不是最全面的.
您实际上不需要在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());
Run Code Online (Sandbox Code Playgroud)
这是我用来解决这个问题的解决方案.
$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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5876 次 |
| 最近记录: |