ZF2 Curl not sending post values

折月煮酒 提交于 2019-12-22 16:30:56

问题


Im trying to use the native Zend Framework 2 http\curl libraries, I can get it to send the request to the remote application I am just unable to get it to POST values to it.

Here is my code that shows 2 examples, the first one is using native PHP curl and it works fine, the second one is using the ZF2 http\curl libraries and it does not pass any of the POST parameters.

Example 1 (Native PHP libraries)

    $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

Example 2 (ZF2 library usage)

    $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());

Is anyone able to point out where i am going wrong with this? I have looked over the ZF2 documents but they are not the most comprehensive.


回答1:


You don't really need to specify all those details on the Curl adapter. That is something ZF2 does for you:

$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());



回答2:


This is the solution I used to fix this issue.

    $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);


来源:https://stackoverflow.com/questions/15523729/zf2-curl-not-sending-post-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!