Пример #1
0
  @Override
  public void run() throws Exception {
    HttpRequest request = HttpRequest.newBuilder().uri(SERVICE_URI + "testAsync/stream").build();
    AsyncHttpClient<ByteBuffer> client =
        AsyncHttpClientBuilder.withApacheAsyncClient().buildClient();
    try {
      Future<HttpResponse> response =
          client.execute(
              request,
              new SSEDecoder(),
              new ResponseCallback<HttpResponse, String>() {
                @Override
                public void completed(HttpResponse response) {}

                @Override
                public void failed(Throwable e) {
                  e.printStackTrace();
                }

                @Override
                public void contentReceived(String element) {
                  System.out.println("Get content from server: " + element);
                }

                @Override
                public void cancelled() {}

                @Override
                public void responseReceived(HttpResponse response) {}
              });
      response.get().close();
    } finally {
      client.close();
    }
  }
 @Override
 public void run() throws Exception {
   HttpRequest request = HttpRequest.newBuilder().uri(SERVICE_URI + "testAsync/stream").build();
   ObservableAsyncClient<HttpRequest, HttpResponse, ByteBuffer> observableClient =
       AsyncHttpClientBuilder.withApacheAsyncClient().observableClient();
   final AtomicReference<HttpResponse> httpResponse = new AtomicReference<HttpResponse>();
   final AtomicInteger counter = new AtomicInteger();
   try {
     observableClient
         .stream(request, new SSEDecoder())
         .toBlockingObservable()
         .forEach(
             new Action1<StreamEvent<HttpResponse, String>>() {
               @Override
               public void call(final StreamEvent<HttpResponse, String> t1) {
                 System.out.println("Content from server: " + t1.getEvent());
                 counter.incrementAndGet();
                 httpResponse.set(t1.getResponse());
               }
             });
   } finally {
     httpResponse.get().close();
     observableClient.close();
     System.out.println("\nTotal event received: " + counter.get());
   }
 }