This commit is contained in:
tursom 2022-04-10 17:25:15 +08:00
parent d74a6def4e
commit 58158b4662
3 changed files with 34 additions and 8 deletions

View File

@ -17,9 +17,8 @@ open class NettyHttpClient : HttpClient {
uri.port
}
val pool = HttpConnectionPool.poolOf(uri.host, port, uri.scheme == "https")
val request = NettyHttpRequest(pool)
val request = NettyHttpRequest(pool, uri.scheme, uri.host, uri.port, uri.path)
request.method = method
request.path = uri.path
return request
}
}

View File

@ -2,6 +2,7 @@ package cn.tursom.web.client.netty
import cn.tursom.core.buffer.ByteBuffer
import cn.tursom.core.buffer.impl.NettyByteBuffer
import cn.tursom.core.toStartWith
import cn.tursom.log.impl.Slf4jImpl
import cn.tursom.web.client.HttpRequest
import cn.tursom.web.client.HttpResponse
@ -13,9 +14,20 @@ import io.netty.handler.codec.http.HttpVersion
class NettyHttpRequest(
private val pool: HttpConnectionPool,
val scheme: String,
val host: String,
val port: Int,
path: String,
) : HttpRequest {
companion object : Slf4jImpl()
private val portStr: String
get() = if (port <= 0) {
""
} else {
":$port"
}
private var request: FullHttpRequest = DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "")
override var version: String
@ -29,11 +41,12 @@ class NettyHttpRequest(
set(value) {
request.method = HttpMethod.valueOf(value)
}
override var path: String
get() = request.uri()
override var path: String = path.toStartWith('/')
set(value) {
request.uri = value
field = value.toStartWith('/')
}
override val params = HashMap<String, ArrayList<String>>().withDefault { ArrayList() }
override fun addParam(key: String, value: String) {
@ -58,6 +71,22 @@ class NettyHttpRequest(
}
override suspend fun send(): HttpResponse {
request.uri = buildString {
append("$scheme://$host$portStr$path")
append(buildString {
params.forEach { (key, params) ->
if (isEmpty()) {
append("?")
}
params.forEach { param ->
if (isNotEmpty()) {
append('&')
}
append("$key=$param")
}
}
})
}
val receiveChannel = pool.useConnection {
it.request(request)
}

View File

@ -13,10 +13,8 @@ internal class NettyHttpClientTest {
runBlocking {
val request = client.request("GET", "https://cdn.segmentfault.com/r-e032f7ee/umi.js")
.addHeader("accept-encoding", "br")
request.path = "https://cdn.segmentfault.com/r-e032f7ee/umi.js"
val response = request.send()
println(response.body
.string())
println(response.body.string())
}
}
}