2

我尝试使用本机 Zend Framework 2 http\curl 库,我可以让它将请求发送到远程应用程序我只是无法让它向它发送值。

这是我的代码,其中显示了 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 文档,但它们并不是最全面的。

4

2 回答 2

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());
于 2013-03-20T13:56:25.567 回答
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);
于 2013-03-21T12:41:48.673 回答