You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Laravel HttpClient实现Postman中的表单请求?

解决Laravel HttpClient发送application/x-www-form-urlencoded请求的问题

你的代码问题分析

  1. 第一种写法错误:
    手动指定withBody的类型为application/json,和你设置的Content-Type: application/x-www-form-urlencoded冲突,导致后端无法正确解析请求参数,返回异常结果。

  2. 第二种写法错误:
    Post方法的第二个参数不需要嵌套form_params键,Laravel HttpClient会自动将数组参数编码为application/x-www-form-urlencoded格式,嵌套form_params会导致后端接收到的参数结构错误(实际参数是form_params[filter]而非filter),无法匹配查询条件。

正确实现方式

根据Postman中实际的请求体结构,选择对应的写法:

场景1:请求参数包含filter(值为JSON字符串)

如果Postman的表单中filter字段的值是类似{"uuid": "xxx"}的JSON字符串,写法如下:

$res = Http::withHeaders([
    'Authorization' => 'Basic ZHh5LWVpbnRlbGxpZxxxxxxxx'
])->post("https://xxxx.com.cn/entity.find", [
    "filter" => json_encode(['uuid' => $uuid]),
]);

场景2:直接传递uuid作为表单参数

如果Postman的表单中直接有uuid字段,写法如下:

$res = Http::withHeaders([
    'Authorization' => 'Basic ZHh5LWVpbnRlbGxpZxxxxxxxx'
])->post("https://xxxx.com.cn/entity.find", [
    "uuid" => $uuid,
]);

调试建议

  • 不需要手动设置Content-Type,Laravel HttpClient在传递数组参数给post方法时,会自动设置Content-Type: application/x-www-form-urlencoded。
  • 对比Postman的请求体,确认参数的键名和格式是否和代码一致(比如filter是否需要JSON字符串)。
  • 可以用$res->body()查看后端返回的原始内容,或者$res->dump()打印完整请求信息,排查参数是否正确发送。

内容的提问来源于stack exchange,提问作者kerby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:24:24