获取 Java 可关闭响应主体的值

Get values of a Java closable response body

我正在从 Binance 获取一份数据列表,其中包含 returns 一个响应,我该如何访问响应正文的值?

private Closeable candleStick(){
        BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient();
        return client.onCandlestickEvent("btcusdt", CandlestickInterval.FIVE_MINUTES, new BinanceApiCallback<com.binance.api.client.domain.event.CandlestickEvent>() {
            @Override
            public void onResponse(com.binance.api.client.domain.event.CandlestickEvent response) {
                System.out.println(response);
            }
        });
    }

响应具有 response.getHigh(), response.getLow() 等值。如何在另一种方法中访问这些值。它

private String show() throws IOException {
        Double high = candleStick().getHigh() //didn't work as the method returns a closeable object.
    }

这是一个基于 API 的回调,因此您应该将应用中的某些数据结构更新为 add/show 新值,而不是您的 System.out.println(...)。

举个简单的例子:

public class CandleStickDataSource {

  private final BinanceApiWebSocketClient client;
  private final Closeable socket;

  private final List<Double> highs = new ArrayList<>();
  private final List<Double> lows = new ArrayList<>();

  private Double lastHigh;    
  private Double lastLow;

  public CandleStickDataSource(String ticker, CandlestickInterval interval) {
    this.client = BinanceApiClientFactory.newInstance().newWebSocketClient();
    this.socket = client.onCandlestickEvent(ticker, interval, new BinanceApiCallback<CandlestickEvent>() {
            @Override
            public void onResponse(CandlestickEvent response) {
                lastHigh = Double.valueOf(response.getHigh());
                lastLow = Double.valueOf(response.getLow()); 
                highs.add(lastHigh);
                lows.add(lastLow);
            }
        });  //  don't forget to call close() on this somewhere when you're done with this class
  }

  public List<Double> getHighs() { return highs; }
  public List<Double> getLows() { return lows; }
  public Double getLastHigh() { return lastHigh; }
  public Double getLastLow() { return lastLow; }

}

因此,在您的应用程序中您想访问数据的其他地方:

CandleStickDataSource data = new CandleStickDataSource("btcusdt", CandlestickInterval.FIVE_MINUTES); // Create this first. This is now reusable for any ticker and any interval

然后当你想查看数据时

data.getHighs(); // history
data.getLows();
data.getLastHigh(); // or getLastLow() for latest values