【问题标题】:Send post request with json object data in Laravel在 Laravel 中发送带有 json 对象数据的 post 请求
【发布时间】:2021-10-07 04:07:06
【问题描述】:

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

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

我的数据变量值:

        $data = [
        "document" => [
            "customerId" => 1,
            "currencyId" => 1,
            "settlementPolicyId" => 8,
            "storeId" => 16,
            "documentPatternId" => 2,
            "items" => [
                [
                    "productId" => 193,
                    "unitId" => 2,
                    "quantity" => 1,
                    "storeId" => 16,
                    "TrackingFactor1" => "1214",
                    "PartTrackingFactorRef1" => 1053,
                    "TrackingFactorHasQuantity1" => true,
                    "TrackingFactorValue" => "‏test",
                    "fee" => 0
                ]
            ]
        ],
        "payments" => [
            [
                "key" => "Cash",
                "amount" => 445810,
                "attr" => []
            ]
        ]
    ];

错误:

TypeError Argument 2 passed to Illuminate\Http\Client\PendingRequest::post() must be of the type array, string given

【问题讨论】:

  • 你能显示完整的代码 $data 包含什么以及你得到什么错误
  • @JohnLobo 是的,我添加了
  • 您遇到了什么错误?最好先在邮递员中检查 api 是否适用于此数据。
  • @JohnLobo 错误:TypeError 参数 2 传递给 Illuminate\Http\Client\PendingRequest::post() 必须是数组类型,给定字符串
  • $data 必须是数组。您正在传递字符串,但根据您的问题 $data is array.may be you are modified $data before pass http

标签: php json laravel api


【解决方案1】:

您可以尝试使用withBody 方法

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

【讨论】:

    【解决方案2】:

    在将json_encode($data) 发送到请求之前。

    $myArray = json_encode($data);
     $finalData = explode(' ',$myArray);
    

    【讨论】:

    • TypeError 参数 2 传递给 Illuminate\Http\Client\PendingRequest::post() 必须是数组类型,给定字符串,
    • ErrorException explode(): 空分隔符
    • 如果explode 不适合你使用 $ary = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);准备好你的字符串。希望它可以帮助你。
    猜你喜欢
    • 2019-01-06
    • 2020-01-11
    • 2017-09-18
    • 2014-06-06
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多