Apache HTTPClient - 使用不确定的 HTTP GET 流
Apache HTTPClient - consume an indefinite HTTP GET Stream
英国的 Companies House 最近发布了 HTTP 'stream' webservice 以允许开发人员无限期地收听公司变更。
下面是他们帮助页面的重要部分
Establishing a connection to the streaming APIs involves making a
long-running HTTP request, and incrementally processing each response
line. Conceptually, you can think of this as downloading an infinitely
long file over HTTP.
使用 Apache HTTP 客户端,我可以使用以下 kotlin 代码 'stream' 在 http 客户端库的调试控制台输出中看到公司更改
val httpClient = HttpClients.createDefault()
val request = HttpGet("https://stream.companieshouse.gov.uk/companies")
request.addHeader("Authorization", "xxxxxxxxxxxxx");
httpClient.execute(request).use { response1 ->
val entity: HttpEntity = response1.entity
entity.content?.use { inputStream -> println("output-->" + String(inputStream.readAllBytes())) }
}
然而,我的控制台输出从未命中(即上面'output-->'的打印字符串)
问题:使用 Apache HTTP 客户端,是否可以使用无限期的 HTTP Get 连接?如果是这样,如何?
您可以通过使用从 HTTP 响应实体无限期返回的流来实现此行为。
这里有一个 Java 示例,说明您将如何做到这一点。
var request = new HttpGet("https://stream.companieshouse.gov.uk/companies");
request.addHeader(HttpHeaders.AUTHORIZATION, auth);
try (var stream = client.execute(request).getEntity().getContent()) {
var buffered = new BufferedReader(new InputStreamReader(new BufferedInputStream(stream)));
while (true) {
String value = buffered.readLine();
if(!value.isBlank()) {
System.out.printf("Event: %s ", value);
}
}
}
应该可以将代码段转换为 Kotlin。
英国的 Companies House 最近发布了 HTTP 'stream' webservice 以允许开发人员无限期地收听公司变更。
下面是他们帮助页面的重要部分
Establishing a connection to the streaming APIs involves making a long-running HTTP request, and incrementally processing each response line. Conceptually, you can think of this as downloading an infinitely long file over HTTP.
使用 Apache HTTP 客户端,我可以使用以下 kotlin 代码 'stream' 在 http 客户端库的调试控制台输出中看到公司更改
val httpClient = HttpClients.createDefault()
val request = HttpGet("https://stream.companieshouse.gov.uk/companies")
request.addHeader("Authorization", "xxxxxxxxxxxxx");
httpClient.execute(request).use { response1 ->
val entity: HttpEntity = response1.entity
entity.content?.use { inputStream -> println("output-->" + String(inputStream.readAllBytes())) }
}
然而,我的控制台输出从未命中(即上面'output-->'的打印字符串)
问题:使用 Apache HTTP 客户端,是否可以使用无限期的 HTTP Get 连接?如果是这样,如何?
您可以通过使用从 HTTP 响应实体无限期返回的流来实现此行为。
这里有一个 Java 示例,说明您将如何做到这一点。
var request = new HttpGet("https://stream.companieshouse.gov.uk/companies");
request.addHeader(HttpHeaders.AUTHORIZATION, auth);
try (var stream = client.execute(request).getEntity().getContent()) {
var buffered = new BufferedReader(new InputStreamReader(new BufferedInputStream(stream)));
while (true) {
String value = buffered.readLine();
if(!value.isBlank()) {
System.out.printf("Event: %s ", value);
}
}
}
应该可以将代码段转换为 Kotlin。