June 17, 2020
By: Dirk

clj-http使用

  1. GET请求
  2. POST请求

在项目开发过程中,无论是前端与后端通信,还是后端与第三方系统通信(如:微信)一般都是通过基于http协议的接口调用形式完成的。前端与后端通信可以借助于浏览器,发送ajax请求来实现,而后端与第三方系统通信有很多框架来完成,用的最多的就是Apache HttpClientclj-http是对Apache HttpClient 封装的clojure版本。

使用clj-http的方法非常简单,分为以下3步:

  1. 引入jar包,在project.cljdependencies引入

    [clj-http "3.10.1"]
    
  2. 在应用中引入clj-http

    (ns my-app.core
        (:require [clj-http.client :as http]))
    
  3. 使用

    根据业务场景选择使用方式

前面提到过http-clj主要用来实现与第三方系统通信(http协议接口),在介绍使用方法之前,先看下接口的组成。接口一般由4部分组成:

  1. 请求地址 (url)
  2. 请求方法 (get / post ...)
  3. 请求参数及传递方式 (header / query / path / form / body ...)
  4. 返回结果

调用接口的过程就是组装1,2,3步的数据,借助于http-clj获取返回结果的过程。

现在介绍几种开发中常用的接口调用方式。

GET请求

;; 基本使用
(http/get "https://blog.3vyd.com")

;; query 参数传递 如:https://blog.3vyd.com?a=xx&b=xxx
(http/get "https://blog.3vyd.com" 
          {:query-params {:a xx
                          :b xxx}})

;; header 参数传递
(http/get "https://blog.3vyd.com"
          {:headers {:authorization "token值"}})

POST请求

;; form 表单参数传递
(http/post "https://blog.3vyd.com"
           {:form-params {:a xx}})

;; form 表单参数传递,指定为json格式
(http/post "https://blog.3vyd.com"
           {:form-params {:a xx}
            :content-type :json})

;; form 表单传递参数,指定编码格式
(http/post "https://blog.3vyd.com"
           {:form-params {:a xx}
            :form-param-encoding "UTF-8"})

;; body 方式传参
(http/post "https://blog.3vyd.com"
             {:body "data"})

;; body 方式传参,指定编码格式
(http/post "https://blog.3vyd.com"
           {:body "data"
            :body-encoding "UTF-8"})

;; body 方式传参,指定json格式
(http/post "https://blog.3vyd.com"
           {:body (clojure.data.json/write-str {:a "xx"
                                                :b "xxx"})
            :content-type :json})

;; 文件上传 (POST / FORM 格式, FORM 表单格式上传y文件)
;; header 参数指定 Content-Type 为 "multipart/form-data"
;; multipart 参数中必须有 name 为 file 的属性,content 值为具体的文件,非路径
(http/post "https://blog.3vyd.com"
           {:headers {:Content-Type "multipart/form-data"}
            :multipart [{:name "file" :content file}]})

;; 返回结果转换为流 (返回结果为流时使用)
;; 如果返回结果类型为 String,此方法也会将 String 转换为流,不报错,使用时要注意
;; 建议处理返回结果时,先判断 Content-Type
;; 返回结果为 java.io.FilterInputStream
(http/get "https://blog.3vyd.com"
           {:as :stream})

更多高级用法可以查看clj-http说明文档: https://github.com/dakrone/clj-http

Tags: clojure clj-http