feiyu02
2024-08-02 16b961c2210fe29fd494ac1f9d830dd93503961f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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")
    }
 
}