Scala 通過HttpClients發送get和post請求

Scala 通過HttpClients發送get和post請求

由於之前的工程代碼都是使用Scala開發的,而最近工作中涉及到一個新功能需要發送post請求後端接口,今把如何使用HttpClients做個筆記。

get請求

def getResponse(url: String, header: String = null): String = {
    val httpClient = HttpClients.createDefault()    // 創建 client 實例
    val get = new HttpGet(url)    // 創建 get 實例

    if (header != null) {   // 設置 header
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => get.setHeader(key, json.getString(key)))
    }

    val response = httpClient.execute(get)    // 發送請求
    EntityUtils.toString(response.getEntity)    // 獲取返回結果
  }

上述代碼還是比較簡單的,創建client並獲取get實例,然後設置header信息,最後直接執行發送請求即可獲取結果

post請求

def postResponse(url: String, params: String = null, header: String = null): String ={
    val httpClient = HttpClients.createDefault()    // 創建 client 實例
    val post = new HttpPost(url)    // 創建 post 實例

    // 設置 header
    if (header != null) {
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => post.setHeader(key, json.getString(key)))
    }

    if (params != null) {
      post.setEntity(new StringEntity(params, "UTF-8"))
    }

    val response = httpClient.execute(post)    // 創建 client 實例
    EntityUtils.toString(response.getEntity, "UTF-8")   // 獲取返回結果
  }

和get方式一樣,唯一不同的地方就是多了設置post參數

完整代碼如下

需要在pom文件中添加如下依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.9</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
com.jmzhou.http

import com.alibaba.fastjson.JSON
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils


/**
  * Created by zhoujiamu on 2019/1/9.
  */
object MyHttpResponse {

  def getResponse(url: String, header: String = null): String = {
    val httpClient = HttpClients.createDefault()    // 創建 client 實例
    val get = new HttpGet(url)    // 創建 get 實例

    if (header != null) {   // 設置 header
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => get.setHeader(key, json.getString(key)))
    }

    val response = httpClient.execute(get)    // 發送請求
    EntityUtils.toString(response.getEntity)    // 獲取返回結果
  }

  def postResponse(url: String, params: String = null, header: String = null): String ={
    val httpClient = HttpClients.createDefault()    // 創建 client 實例
    val post = new HttpPost(url)    // 創建 post 實例

    // 設置 header
    if (header != null) {
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => post.setHeader(key, json.getString(key)))
    }

    if (params != null) {
      post.setEntity(new StringEntity(params, "UTF-8"))
    }

    val response = httpClient.execute(post)    // 創建 client 實例
    EntityUtils.toString(response.getEntity, "UTF-8")   // 獲取返回結果
  }


  def main(args: Array[String]): Unit = {

    val url = "http://192.168.1.00:8082/risk/getUserByGet?userName=zhoujiamu"

    println("This get response: ")
    println(getResponse(url))

    val postUrl = "http://192.168.1.00:8082/risk/group"
    val params = """{"company_list":["北京佛爾斯特金融信息服務有限公司"],"conditions":{}}"""

    println("This post response: ")
    println(postResponse(postUrl, params, """{"Content-Type": "application/json"}"""))

  }

}

運行結果如下:

This get response: 
Hello zhoujiamu
This post response: 
{ "group_name":"P2P風險傳導場景", "vertices":[{"_id":"Virtual/D41D8CD98F00B204E9800998ECF8427E","name":"泛化條件點","pr":"0.0","is_source":"false","main_path_list":[]},{"name":"錢滿倉","_id":"Platform/36FFFD6CDAE2C688EC0879E05D3305B8","pr":"0.0","is_source":"false","main_path_list":[]}],"edges":[{"similarity":1.0,"_to":"Virtual/D41D8CD98F00B204E9800998ECF8427E","_from":"Platform/36FFFD6CDAE2C688EC0879E05D3305B8","label":"問題P2P平臺","_id":"generalized/36FFFD6CDAE2C688EC0879E05D3305B8","is_main_path":"false"},{"_to":"Platform/36FFFD6CDAE2C688EC0879E05D3305B8","_from":"Company/A245F7AA7A271C4CD6D7C374A19F52E7","label":"經營","_id":"manage/42F73DE7FC64E70792977F681EAA23AE","is_main_path":"false"}] }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章