ZF2 Curl 不发送帖子值 [英] ZF2 Curl not sending post values

查看:19
本文介绍了ZF2 Curl 不发送帖子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用原生 Zend Framework 2 http\curl 库,我可以让它将请求发送到远程应用程序,我只是无法将它的值发送给它.

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.

这是我的代码,其中显示了 2 个示例,第一个使用本机 PHP curl 并且工作正常,第二个使用 ZF2 http\curl 库并且不传递任何 POST 参数.

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.

示例 1(本机 PHP 库)

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

示例 2(ZF2 库使用)

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

有人能指出我哪里出错了吗?我查看了 ZF2 文档,但它们不是最全面的.

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.

推荐答案

这是我用来解决此问题的解决方案.

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

这篇关于ZF2 Curl 不发送帖子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆