Clojure 如何在环中模拟json post请求?
我正在使用peridot-测试我的ring应用程序,在我尝试用json数据模拟post请求之前,它工作正常: (require '[cheshire.core :as json]) (use 'compojure.core) (defn json-post [req] (if (:body req) (json/parse-string (slurp (:body req))))) (defroutes all-routes (POST "/test/json" req (json-response (json-post req)))) (def app (compojure.handler/site all-routes)) (use 'peridot.core) (-> (session app) (request "/test/json" :request-method :post :body (java.io.ByteArrayInputStream. (.getBytes "hello" "UTF-8"))) (需要“[cheshire.core:as json]”) (使用“compojure.core”) (defn-json-post[req] (如果(:主体要求) (json/parse字符串(slurp(:body req‘‘‘‘)’) (取消所有路线的路线) (POST“/test/json”请求(json响应(json POST请求))) (def应用程序(compojure.handler/site all routes)) (使用“橄榄石核心”) (>(会话应用程序) (请求“/test/json” :申请方式:邮寄 :body(java.io.ByteArrayInputStream.(.getBytes“hello”“UTF-8”)) 给出Clojure 如何在环中模拟json post请求?,clojure,ring,Clojure,Ring,我正在使用peridot-测试我的ring应用程序,在我尝试用json数据模拟post请求之前,它工作正常: (require '[cheshire.core :as json]) (use 'compojure.core) (defn json-post [req] (if (:body req) (json/parse-string (slurp (:body req))))) (defroutes all-routes (POST "/test/json" req (
IOException:stream closed
有更好的方法吗?tldr:
当peridot生成请求映射时,对于
:post
请求的内容类型,它将默认为应用程序/x-www-form-urlencoded
。使用指定的应用程序wrap params
(包含在compojure.handler/site
中)将尝试读取:body
,以解析任何形式的URL编码参数。然后json post
尝试再次读取:body
。但是InputStream
被设计为只读取一次,这会导致异常
解决这个问题基本上有两种方法:
compojure.handler/site
.getBytes
,只需使用:body
参数传递json即可
(-> (session app)
(request "/test/json"
:request-method :post
:content-type "application/json"
:body (.getBytes "\"hello\"" "UTF-8")))
(require '[cheshire.core :as json])
(-> (session app)
(request "/test/json"
:request-method :post
:content-type "application/json"
:body (json/generate-string data))