【问题标题】:How to send form fields with Guzzle 6?如何使用 Guzzle 6 发送表单字段?
【发布时间】:2025-12-27 04:10:11
【问题描述】:

我正在为在 Symfony4 中创建的 API 开发我的单元测试

阅读 Guzzle 文档,我生成了以下代码:

文件 SecurityControllerTest.php

    $client = new Client([
        'base_uri' => 'http://localhost/sacrepad/sacrepad-api/public/index.php/',
        'timeout'  => 2.0,
    ]);
    $data = array();
    $data['email'] = 'admin@admin.com';
    $data['password'] = '12345678';
    $data2 = array();
    $data2['json'] = $data;
    $formData = json_encode($data);
    $response = $client->request('POST', 'login', [
        'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
        'form_params' => [
            'json' => $formData,
        ]
    ]);
    $body = json_decode($response->getBody(), true);

文件 SecurityController.php

/**
 * @Route("/login", name="login", methods={"POST"})
 */
public function login(Request $request,Helpers $helpers,ValidatorInterface $validator, JwtAuth $jwtauth) {

    $data = array(
        'status' => 'error',
        'code' => 400,
        'msg' => 'data not received'
    );

    $json = $request->request->get('json');
    $params = json_decode($json);
}

当我使用 phpunit 命令运行测试时,我收到以下错误:

1) App\Tests\SecurityControllerTest::testAuth GuzzleHttp\Exception\ServerException: Server error: `POST http://localhost/sacrepad/sacrepad-api/public/index.php/login` resulted in a `500 Internal Server Error` response:

如果我更改请求的名称:

$json = $request->request->get('json2');

它有效,它返回以下内容:

array(3) {
  ["status"]=>
  string(5) "error"
  ["code"]=>
  int(400)
  ["msg"]=>
  string(18) "data not received"
}

关于如何使其工作和发送参数的任何想法?

【问题讨论】:

    标签: php api http symfony4 guzzle


    【解决方案1】:

    我建立了一个使用 guzzle 的类

     use Exception;
     use GuzzleHttp\Client;
     use GuzzleHttp\Exception\RequestException;
    
    
    class Api
    {
    
    protected $client;
    protected $url;
    
    public function __construct()
    {
        $this->client = new Client([
            'verify'=>false
        ]);
        $this->url = 'http://localhost/sacrepad/sacrepad-api/public/';
    
    }
    
    public function get($endpoint, $params = [], $headers = [])
    {
        $response = $this->sendRequest(
            'GET',
            $this->url . $endpoint,
            $params,
            $headers
        );
        return $response;
    }
    
    public function post($endpoint, $params = [], $headers = [])
    {
    
        $response = $this->sendRequest(
            'POST',
            $this->url . $endpoint,
            $params,
            $headers
        );
    
        return $response;
    }
    
    public function sendRequest($type, $url, $params = [], $headers = [])
    {
    
        if ($type == 'GET') {
            $data = [
                'query' => $params
            ];
        } elseif ($type == 'FILE') {
            $type = 'POST';
            $data = [
                'multipart' => $params // TODO implements later
            ];
        } else {
            $data = [
                'json' => $params
            ];
        }
    
        if (!empty($headers)) {
            $data['headers'] = $headers;
        }
    
        $data['headers']['X-REAL-IP'] = $_SERVER['REMOTE_ADDR'];
        $data['headers']['User-Agent'] = $_SERVER['HTTP_USER_AGENT'];;
        $data['headers']['X-Platform'] = 'web';
    
        try {
    
    
            $response = $this->client->request(
                $type,
                $url,
                $data
            );
    
    
            if (in_array($response->getStatusCode(), ['200', '403', '404'])) {
                return json_decode($response->getBody());
            }
    
    
            return false;
        } catch (RequestException $re) {
    
            if (in_array($re->getResponse()->getStatusCode(), ['403', '404', '422'])) {
                return json_decode($re->getResponse()->getBody());
            }
            return json_decode($re->getResponse()->getBody());
        } catch (Exception $e) {
            return false;
        }
    }
    }
    

    当我想发送一个帖子请求时,它会是这样的

    $response = (new Api())->post('index.php/',[
            'email'=> 'admin@admin.com',
            'password' => '123456'
        ]);
    

    现在它将向 index.php 发送一个 post 请求并发送电子邮件和密码数据,我希望它会有所帮助

    【讨论】:

      最近更新 更多