Commit e7393403 authored by 杨林's avatar 杨林

请求网络工具

parent e1866026
package tools.http
import java.util.Properties
import com.alibaba.fastjson.JSON
import org.apache.http.client.methods.{HttpGet, HttpPost, HttpRequestBase}
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.util.EntityUtils
import tools.json.Jackson
import tools.properties.PropertiesTools
import tools.unicode.UnicodeUtils
import scala.collection.mutable
/**
* @ClassName: qm.tools.http
* @Description: 请求网络工具
* @Author: LinYoung
* @Date: 2021/5/26
* @Time: 11:25
*/
object HttpTools {
private[this] val properties: Properties = PropertiesTools.getProperties
private[this] val url = properties.getProperty("nlp.interface.url")
def apply(method: String): HttpTools = new HttpTools(method, this.url)
def main(args: Array[String]): Unit = {
val str = apply("POST").nlp_request("男钱包男钱夹男短款票夹驾驶证钱夹手拿多用票夹横款钱包")
println(str)
}
}
class HttpTools(method: String, url: String, header: String =
"""
|{"Content-Type":"application/json"}
|""".stripMargin) {
// 创建请求客户端
private[this] val httpClient: CloseableHttpClient = HttpClients.createDefault()
// 创建基本请求
private[this] var httpRequest: HttpRequestBase = _
// 判断请求的方式
if (method == "GET") {
httpRequest = new HttpGet(url)
}
else if (method == "POST") {
httpRequest = new HttpPost(url)
}
// 定义请求头
if (header != null) {
val json = JSON.parseObject(header)
json.keySet().toArray.map(_.toString).foreach(key => httpRequest.setHeader(key, json.getString(key)))
}
/**
* 请求分词工具方法
*
* @param params 要分词的标题
* @return 分词结果
*/
def nlp_request(params: String): String = {
if (params != null) {
val body: mutable.Map[String, String] = mutable.Map()
body += ("text" -> params)
val str = Jackson.parseBeanToString(body)
httpRequest.asInstanceOf[HttpPost].setEntity(new StringEntity(str, "utf-8"))
}
val response = httpClient.execute(httpRequest)
val str = EntityUtils.toString(response.getEntity, "utf-8")
val map = Jackson.parseFirstKey(UnicodeUtils.decode(str))
val code = map.getOrElse("code", "0").toInt
val msg = map.getOrElse("msg", "").replaceAll("\"", "")
if (code == 200 && msg.equals("success")) {
map.getOrElse("data", "").replaceAll("\"", "")
}
else ""
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment