2013-03-20 49 views
2

我试图使用原生Zend Framework 2 http \ curl库,我可以让它发送请求到远程应用程序,我只是无法获得它的POST值到它。ZF2 Curl不发送帖子值

这是我的代码,显示了2个例子,第一个使用本地PHP卷曲并且工作正常,第二个使用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文件,但它们并不是最全面的。

回答

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); 
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()); 
+0

对不起,它已经采取了应对时间。这是由于'$ request-> setBody($ postString);'方法不存在导致错误。 – 2013-03-21 08:07:10

+0

我的不好,它是'setContent'。解决答案。 – Ocramius 2013-03-21 08:12:10

+0

非常感谢,最后我终于找到了一个不同的解决方案。但这似乎也起作用。 – 2013-03-21 12:42:36