使用Java访问响应中的单个SSE有效负载

qgzx9mmu  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(187)

我们目前使用Apache HttpClient(5)向服务器发送POST请求,响应通过服务器端事件(SSE)返回给我们,SSE包含多个有效负载,使用标准格式:

data: {...}

目前我们有这样的代码发送请求和接收响应:

// Set the socket timeout
final ConnectionConfig connConfig = ConnectionConfig.custom()
                    .setSocketTimeout(socketTimeout, TimeUnit.MILLISECONDS)
                    .build();

// Custom config
final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
            cm.setConnectionConfig(connConfig);

// Build the client
try (final CloseableHttpClient client = HttpClientBuilder.create().setConnectionManager(cm).build()) {

      // Execute the request
      return client.execute(request.getRequest(),

              // Get and process the response          
              response -> HttpResponse.builder()
                              .withCode(response.getCode())
                              .withContent(EntityUtils.toByteArray(response.getEntity()))
                              .build()
                );

      }

这一切都工作得很好,除了我需要在响应到达时访问响应中的各个传入响应有效负载(data {...}),而不是等待它们全部完成才能访问响应。
如果使用Apache这是不可能的,我愿意接受其他的选择,只要他们可以发送一个正常的HTTP(S)POST

k97glaaz

k97glaaz1#

好吧,我不能让它与Apache Client一起工作,但我确实找到了这个video,它展示了如何使用本机HttpClient来完成它。

// Create the client
final HttpClient client = HttpClient.newHttpClient();

// Make the request 
final HttpResponse<Stream<String>> response = client.send(request, HttpResponse.BodyHandlers.ofLines());

// Status code check
if (response.statusCode() != 200) ...;

// This will consume individual events as they arrive
response.body().forEach(System.out::println);

相关问题