HTTP Client Response

预计阅读时间:2分钟

Receiving the body of a response

默认情况下,您可以将HttpResponseString用作键入的HttpClient请求的可能类型. 因此,例如:

val htmlContent = client.get<String>("https://en.wikipedia.org/wiki/Main_Page")
val response = client.get<HttpResponse>("https://en.wikipedia.org/wiki/Main_Page")

如果配置了JsonFeature ,并且服务器返回标头Content-Type: application/json ,那么您还可以指定用于反序列化的类.

val helloWorld = client.get<HelloWorld>("http://127.0.0.1:8080/")

The HttpResponse class

此处列出 HttpResponse API参考.

HttpResponse ,您可以轻松获取响应内容:

  • val readChannel: ByteReadChannel = response.content
  • val bytes: ByteArray = response.readBytes()
  • val text: String = response.readText()
  • val readChannel = response.receive<ByteReadChannel>()
  • val multiPart = response.receive<MultiPartData>()
  • val inputStream = response.receive<InputStream>() 请记住,InputStream API是同步的!
  • response.discardRemaining()

您还可以获取其他响应信息,例如其状态,标头,内部状态等:

Basic

  • val status: HttpStatusCode = response.status
  • val headers: Headers = response.headers

Advanced

  • val call: HttpClientCall = response.call
  • val version: HttpProtocolVersion = response.version
  • val requestTime: Date = response.requestTime
  • val responseTime: Date = response.responseTime
  • val executionContext: Job = response.executionContext

Extensions for headers

  • val contentType: ContentType? = response.contentType()
  • val charset: Charset? = response.charset()
  • val lastModified: Date? = response.lastModified()
  • val etag: String? = response.etag()
  • val expires: Date? = response.expires()
  • val vary: List<String>? = response.vary()
  • val contentLength: Int? = response.contentLength()
  • val setCookie: List<Cookie> = response.setCookie()

by  ICOPY.SITE