Kotlin okhttp 动态标头
我正在使用 okhttp (不是改造)向 api 发出所有请求。它工作得很好,但我在制作动态标题时遇到了一些麻烦。这就是我所做的:
private fun buildRequest(url: String, methode: Method = Method.GET, filters: Map<String, String> = mapOf(): Request? {
var builder = FormBody.Builder()
builder.add("body", "test")
val request = Request.Builder()
.url(url)
.addHeader("API-Key", apikey)
.post(formBody)
.build()
}
问题是我有一个地图过滤器,它代表我需要添加的一些标头,但这些不是硬编码的,但它们是动态的,例如可以是:
var filters = mapOf("limit" to "10", "sort" to "date")
但我不能为过滤器,因为我不知道我是否会有一些过滤器,或者它们会是什么。
我的想法是像这样使用 newBuilder :
if (!filters.isNullOrEmpty()){
filters.forEach{
request.newBuilder()
request.addHeader(it.key, it.value)
.build()
}
问题是这不会将我的新标头添加到调用中。我是否缺少有关如何使用 newBuilder 的信息?或者有没有办法用 okhttp 管理动态标头?
i am using okhttp (not retrofit) to make all my request to the api. It's working perfectly but i am having some trouble to make dynamique header. here is what i did :
private fun buildRequest(url: String, methode: Method = Method.GET, filters: Map<String, String> = mapOf(): Request? {
var builder = FormBody.Builder()
builder.add("body", "test")
val request = Request.Builder()
.url(url)
.addHeader("API-Key", apikey)
.post(formBody)
.build()
}
Problem is that i got a map filter that represent some header i need to add, but those are not hard coded but they are dynamique, it can be for exemple :
var filters = mapOf("limit" to "10", "sort" to "date")
But i can't do a static addHeader for the filters because i don't know if i am going to have some or not or which are they going to be.
My idea was to use newBuilder like this :
if (!filters.isNullOrEmpty()){
filters.forEach{
request.newBuilder()
request.addHeader(it.key, it.value)
.build()
}
Problem is that this doesn't add my new header to the call. I am I missing something on how to use newBuilder ? or is there a way to manage dynamique header with okhttp ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
map
的toHeaders()
扩展函数将您的map
对象转换为Headers
。地图的所有键值对都可以轻松添加到标题中,如下所示
您还可以稍后使用
newBuilder()
将标头添加到request
构建器You can use
toHeaders()
extension function ofmap
to convert yourmap
object toHeaders
.All key-value pairs of the map can be easily added to headers like this
You can also add headers to
request
builder later, on usingnewBuilder()