symfony 4在进程中创建post请求

yx2lnoni  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(110)

我想创建一个函数,它将执行其他的URL(这个URL在服务器上生成文件),并得到响应,然后发送消息给用户,但我不想使用Askin,我试图使用Reqeust对象,但它不工作。

public function testCreateFile() {

    $uri = 'http://someuri/somefuncition';
    $method = 'POST';
    $paramaters = array(
        'csv' => '20190102212655-product-test.csv',
        'type' => '5', 

    );
   $request = new Request();
   $request->create($uri,$method,$paramaters);

    return new Response("Message to user") ;
}

我该怎么做才正确?
提前感谢您的帮助。

thtygnil

thtygnil1#

你需要的是 curl。最好的方法是使用下面的代码作为服务,所以我将给予完整的类
服务类

<?php
    App\Services;

    class PostRequest
    {
        static function get_data(String $url, Array $post_parameters)
        {
            //url-ify the data for the POST
            $parameters_string = "";

            foreach($post_parameters as $key=>$value) {
                 $parameters .= $key.'='.$value.'&'; 
            }

            rtrim($fields_string, '&');

            //open connection
            $ch = curl_init();

            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_POST, count($post_parameters));
            curl_setopt($ch,CURLOPT_POSTFIELDS, $parameters);

            //execute post
            $result = curl_exec($ch);

            curl_close($ch);

            return $result;
        }
    }
?>

因此,在Controller中包含use App\Services\PostRequest;后,您可以执行以下操作

public function testCreateFile() {
    $uri = 'http://someuri/somefuncition';
    $paramaters = [
        'csv' => '20190102212655-product-test.csv',
        'type' => '5',
    ];
    $request = PostRequest::get_data($uri, $paramaters);
    return new Response("Message to user") ;
}
ajsxfq5m

ajsxfq5m2#

您可以使用Symfony\Component\HttpClient\HttpClient创建post请求
参见https://zetcode.com/symfony/httpclient/
从这个页面:

use Symfony\Component\HttpClient\HttpClient;

$httpClient = HttpClient::create();

$response = $httpClient->request('POST', 'https://httpbin.org/post', [
    'body' => ['msg' => 'Hello there']
]);

echo $response->getContent();

相关问题