如何在http客户端GET方法中传递对象?

问题描述 投票:0回答:1

我需要在 URL 中传递一个对象来获取数据。我将以下 URL 放入邮递员中以执行结果。

http://my_url/match/?search={"front": {"id": "1000", manufacturer: "Test"}....}

但是,我不确定如何在 symfony 中使用 CURL 传递该对象

$url = "http://my_url/match?search=";

        $response = $this->httpClient->request('GET', $url, [
            'headers' => $this->shopAuth->setHeader(),
            'query' => [
                'search' => $objToPass
            ]
        ]);

我试图通过

query
但结果是这样的:
?search[front][id]=1000&search[front][manufacturer]=Test ........

有人可以帮我吗?

php httpclient symfony5
1个回答
0
投票

当您传递一个数组作为“查询”参数时,Symfony 的 HttpClient 会自动将其转换为带有嵌套键的查询参数。如果您想将 JSON 对象作为 URL 中的查询参数发送,则需要手动将其编码为 JSON 字符串,然后在服务器端对其进行解码。

希望这个参考代码可以帮助你

使用 Symfony\Component\HttpClient\HttpClient;

// Your JSON object to pass
$objToPass = [
    'front' => [
        'id' => '1000',
        'manufacturer' => 'Test'
    ],
    // Add more data here if needed
];

// Encode the object as a JSON string
$jsonString = json_encode($objToPass);

$url = "http://my_url/match?search=" . urlencode($jsonString);

$httpOptions = [
    'headers' => $this->shopAuth->setHeader(),
];

$response = HttpClient::create()->request('GET', $url, $httpOptions);

// Decode the JSON response from the server if needed
$data = json_decode($response->getContent(), true);
© www.soinside.com 2019 - 2024. All rights reserved.