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"}"""))
val header =
"""
|{
| "Accept": "application/json;charset=UTF-8",
| "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
| "Connection": "keep-alive",
| "Content-Type": "application/json; charset=utf-8",
| "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1TVAwU0w4TmVnciIsImV4cCI6MTU5NTU0NzE4MSwidWlkIjozMDR9.uf8VTB4yWh2nl2SmL8GJmDa6zewhMZF2QMh6SIcKFR4"
|}
""".stripMargin
// 需要token认证的情况,在header中加入Authorization
println(postResponse(postUrl, params, header))
}
}
运行结果如下:
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"}] }