在 Laravel 中,发送带有 json 对象数据的 post 请求

Tho*_*mas 5 php api json laravel

我想在 Laravel 中使用 Http Facade 发送请求,但我无法传递 json 对象数据,它必须只是数组。

\n
Http::withHeaders(['Content-Type' => 'application/json'])->withOptions(['headers' => $coockie])->post($this->policy_url . $address, json_encode($data));\n
Run Code Online (Sandbox Code Playgroud)\n

我的数据变量值:

\n
$data = [\n    "document" => [\n        "customerId" => 1,\n        "currencyId" => 1,\n        "settlementPolicyId" => 8,\n        "storeId" => 16,\n        "documentPatternId" => 2,\n        "items" => [\n            [\n              "productId" => 193,\n              "unitId" => 2,\n              "quantity" => 1,\n              "storeId" => 16,\n              "TrackingFactor1" => "1214",\n              "PartTrackingFactorRef1" => 1053,\n              "TrackingFactorHasQuantity1" => true,\n              "TrackingFactorValue" => "\xe2\x80\x8ftest",\n              "fee" => 0\n            ]\n          ]\n        ],\n        "payments" => [\n            [\n                "key" => "Cash",\n                "amount" => 445810,\n                "attr" => []\n            ]\n        ]\n    ];\n
Run Code Online (Sandbox Code Playgroud)\n

错误:

\n
TypeError Argument 2 passed to Illuminate\\Http\\Client\\PendingRequest::post() must be of the type array, string given\n
Run Code Online (Sandbox Code Playgroud)\n

小智 9

您可以尝试使用withBody方法

Http::withBody(json_encode($data), 'application/json')
    ->withOptions([
       'headers' => $coockie
    ])
    ->post($this->policy_url . $address);
Run Code Online (Sandbox Code Playgroud)


Tay*_*har 0

json_encode($data)在发送请求之前先进行制作。

$myArray = json_encode($data);
 $finalData = explode(' ',$myArray);
Run Code Online (Sandbox Code Playgroud)