package cn.flightfeather.supervision.common.net
|
|
import org.apache.commons.httpclient.HttpClient
|
import org.apache.commons.httpclient.HttpMethodBase
|
import org.apache.commons.httpclient.methods.GetMethod
|
import org.apache.commons.httpclient.methods.PostMethod
|
import org.apache.commons.httpclient.methods.StringRequestEntity
|
import org.apache.commons.httpclient.protocol.Protocol
|
|
/**
|
* @author riku
|
* Date: 2020/10/14
|
*/
|
class HttpMethod(
|
private val host: String, private val port: Int, private val isHttps: Boolean = false
|
) {
|
|
data class MyResponse(
|
val success: Boolean,
|
val m: HttpMethodBase
|
)
|
|
object Head {
|
val TEXT_PLAIN = Pair("Content-Type", "text/plain")
|
}
|
|
private val httpClient = HttpClient()
|
|
init {
|
if (isHttps) {
|
httpClient.hostConfiguration.setHost(host, port, Protocol.getProtocol("https"))
|
} else {
|
httpClient.hostConfiguration.setHost(host, port)
|
}
|
}
|
|
fun get(url: String, params: List<Pair<String, String>> = emptyList(), headers: List<Pair<String, String>> = emptyList()): MyResponse {
|
var p: String = ""
|
params.forEach {
|
p += if (p.isBlank()) {
|
it.first + "=" + it.second
|
} else {
|
"&" + it.first + "=" + it.second
|
}
|
}
|
val getMethod = GetMethod("$url?$p")
|
defaultConfig(getMethod)
|
headers.forEach {
|
getMethod.setRequestHeader(it.first, it.second)
|
}
|
|
return when (httpClient.executeMethod(getMethod)) {
|
200 -> MyResponse(true, getMethod)
|
else -> MyResponse(false, getMethod)
|
}
|
}
|
|
fun post(url: String, data: String = "", headers: List<Pair<String, String>> = emptyList()): MyResponse {
|
val postMethod = PostMethod(url)
|
defaultConfig(postMethod)
|
headers.forEach {
|
postMethod.setRequestHeader(it.first, it.second)
|
}
|
if (data.isNotBlank()) {
|
postMethod.requestEntity = StringRequestEntity(data, "application/json", "utf-8")
|
}
|
|
return when (httpClient.executeMethod(postMethod)) {
|
200 -> MyResponse(true, postMethod)
|
else -> MyResponse(false, postMethod)
|
}
|
}
|
|
private fun defaultConfig(method: HttpMethodBase) {
|
method.setRequestHeader("accept", "*/*");
|
method.setRequestHeader("connection", "Keep-Alive");
|
method.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.5");
|
method.setRequestHeader("Content-Type", "application/json;charset=utf-8")
|
}
|
|
}
|