使用 HttpURLConnection 时如何检查是否添加了 header

How to check if the header is added when using HttpURLConnection

我不知道如何编写测试用例来测试header已成功添加。

val connection = URL("http://www.google.com").openConnection() as HttpURLConnection
connection.setRequestProperty("a", "b")
assertEquals("b", connection.getHeaderField("a"))

基本上,getHeaderField 将 return 为空。 getHeaderFields 的结果也不包括这个 a 字段。我检查了连接 object。在运行时有一个名为 userHeaders 的 属性,但我在编码时无法访问它。似乎未包含在 HttpURLConnection 布局中。

如何断言我的 header 已添加?

那么你正在使用 setRequestProperty(...) 为什么不使用 getRequestProperty(...) 断言?

val connection = URL("http://www.google.com").openConnection() as HttpURLConnection
val headers = mapOf("a" to "b")
connection.setRequestProperty("a", "b")
assertEquals("b", connection.getRequestProperty("a")) // OK