【问题标题】:How to set Content-Type as application/json in httpkit如何在 httpkit 中将 Content-Type 设置为 application/json
【发布时间】:2015-07-01 13:07:36
【问题描述】:

我使用httpkit 作为http 客户端。我尝试了许多解决方案来使标题Content-Type 成为application/json,但都失败了。

这是我的代码:

(require '[org.httpkit.client :as http])

(http/post 
  url
  { :query-params {"q" "foo, bar"}
    :form-params {"q" "foo, bar"}
    :headers {"Content-Type" "application/json; charset=utf-8"}})

使用上面的代码发布会得到response status 200,但Content-Typeapplication/x-www-form-urlencoded

如果删除行application/x-www-form-urlencoded,将得到response status 400

PS:我以flask 作为网络服务器。

【问题讨论】:

  • 您是否期望您的 request Content-Type 修改 response Content-Type 标头?如果是这样,那么您应该研究端点在您的 Web 服务器中的实现,而不是客户端。

标签: json clojure http-headers content-type http-kit


【解决方案1】:

您要发送什么请求?

  • :query-params 会将 ?q=foo,bar 附加到请求 url
  • :form-params 将使正文 q=foo,bar 具有内容类型 application/x-www-form-urlencoded

这可能比需要的要多,但身体也必须是application/json,除了已经是application/x-www-form-urlencoded

如果你想要一个 json 正文,你可以这样做:

:body (clojure.data.json/write-str {:q "foo,bar"})

【讨论】:

  • @schaueho,感谢您的编辑,我的格式真的很难看。
【解决方案2】:

我没有使用过httpkit(可以推荐clj-http)但我认为你应该使用:body选项而不是:form-params来指定有效载荷,因为后者将forceContent-Type到@ 987654328@。考虑到form params 在 HTTP 中的工作方式,这是有道理的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 2013-04-07
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2023-04-07
    • 2013-11-24
    • 1970-01-01
    相关资源
    最近更新 更多