Commit b6e355cb authored by 杨林's avatar 杨林

请求网络工具

parent 0457b7f3
package qm.tools.http package qm.tools.http
import java.util.Properties
import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSON
import org.apache.http.client.methods.{HttpGet, HttpPost, HttpRequestBase} 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 qm.tools.json.Jackson
import qm.tools.properties.PropertiesTools
import qm.tools.unicode.UnicodeUtils
import scala.collection.mutable import scala.collection.mutable
...@@ -13,13 +21,15 @@ import scala.collection.mutable ...@@ -13,13 +21,15 @@ import scala.collection.mutable
* @Time: 11:25 * @Time: 11:25
*/ */
object HttpTools { object HttpTools {
private[this] val properties: Properties = PropertiesTools.getProperties
def apply(method: String, url: String, header: String): HttpTools = new HttpTools(method, url, header)
} }
class HttpTools(method: String, url: String, header: String = class HttpTools(method: String, url: String, header: String =
""" """
|{"Content-Type":"application/json"} |{"Content-Type":"application/json"}
|""".stripMargin) { |""".stripMargin) {
private[this] val httpClient: CloseableHttpClient = HttpClients.createDefault()
var httpRequest: HttpRequestBase = _ var httpRequest: HttpRequestBase = _
...@@ -38,7 +48,17 @@ class HttpTools(method: String, url: String, header: String = ...@@ -38,7 +48,17 @@ class HttpTools(method: String, url: String, header: String =
if (params != null) { if (params != null) {
val body: mutable.Map[String, String] = mutable.Map() val body: mutable.Map[String, String] = mutable.Map()
body += ("text" -> params) 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", "")
if (code == 200 && msg.equals("success")) {
map.getOrElse("data", "")
} }
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