2013-03-20 76 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