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

Scala-Requests如何发送x-www-urlencoded格式表单数据?

使用scala-requests发送x-www-form-urlencoded格式数据

scala-requests原生支持application/x-www-form-urlencoded格式,不需要额外特殊方法,但你的代码用法有误,导致请求失败。

问题原因

你传入的data是JSON字符串,而x-www-form-urlencoded要求的是键值对结构(最终编码为name=test&age=12&class=3esasfc这类格式)。即使手动设置了Content-Type,库也不会自动将JSON字符串转换为符合要求的键值对编码内容,因此接口无法解析。

正确写法

直接传入键值对Map

当你将Map[String, Any]类型的数据传给data参数时,scala-requests会自动设置Content-Type为application/x-www-form-urlencoded,并完成编码:

requests.post(
  url = endpoint,
  headers = Map(
    "Authorization" -> s"Bearer $bearerToken"
  ),
  data = Map(
    "name" -> "test",
    "age" -> 12,
    "class" -> "3esasfc"
  )
)

从JSON转换为键值对

如果你的数据原本是JSON结构,需要先将其解析为键值对Map再传入。以circe JSON库为例:

import io.circe.parser._

val jsonStr = """{"name":"test","age":12,"class":"3esasfc"}"""
// 解析JSON为键值对Map
val formData = parse(jsonStr)
  .flatMap(_.as[Map[String, String]])
  .getOrElse(Map.empty)

requests.post(
  url = endpoint,
  headers = Map(
    "Authorization" -> s"Bearer $bearerToken"
  ),
  data = formData
)

注意事项

  • 无需手动设置Content-Type: application/x-www-form-urlencoded,传入Map类型的data时库会自动处理。
  • 如果传入非Map类型的data(比如你的JSON字符串),库会按普通文本发送,即使手动设置Content-Type也无法改变内容格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:50:27