首页 > 解决方案 > 使用 JSON 原始数据请求正文逻辑

问题描述

我正在尝试通过 Postman 作为所需参数发送原始 JSON 数据。

除了那部分,我的功能工作正常。当我将 json 数据粘贴到邮递员中时,它会抛出:

A non-empty request body is required.

我认为需要进行一些修改,但我找不到解决方案。

我的代码:

 public function callApi(BaseRequest $request)
{

    $token = $this->getTokenForRequest($request);
    $method = $request->getMethod();

    $client = new Client(['base_uri' => 'https://api-tst.testing.app/test/']);

    $headers = [
        'Authorization' => 'Bearer ' . $token,
        'Ocp-Apim-Subscription-Key' => '1111112222',
        'Content-Type'  => 'application/json',
    ];

    $request->getRequestParams();

    $res = $client->request($method, $request->getUrl(), [
        'headers' => $headers
    ]);

    $res->getStatusCode();
    $response = $res->getBody()->getContents();

    return $response;
}

并形成我的 BaseRequest:

 public function getUrl()
{
    return null;
}

public function getMethod()
{
    return null;
}

/**
 * @return array
 */
public function getRequestParams()
{
   $data = [];

   return $data;
}

我在控制器中调用它,例如:

 public function testAll(Request $request)
    {
        $data = (string)$request->getContent();
        $data = json_decode($data, true);
        $response = $this->container->get('app')->myFunction($data);

        dump($response);die;
    }

标签: phpjsonsymfonyresponsesymfony-3.4

解决方案


找到了!

 $res = $client->request($method, $request->getUrl(), [
        'headers' => $headers,
        'json' => $request->getRequestParams()
    ]);

推荐阅读