在Java中读取text/event-stream数据,可以使用Java中的HttpURLConnection和InputStream来实现。下面是一个简单的示例代码: ```java import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class EventStreamReader { public static void main(String[] args) throws Exception { // 创建URL对象 URL url = new URL("http://example.com/event-stream"); // 替换为实际的URL // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "text/event-stream"); // 获取输入流 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // 处理每行数据 System.out.println(line); } // 关闭连接和输入流 reader.close(); connection.disconnect(); } } ``` 这段代码通过建立一个HTTP连接来获得text/event-stream格式的数据流,并使用`BufferedReader`逐行读取数据。你可以根据实际情况对每行数据进行处理。 需要注意的是,这段代码是一个简单示例,实际使用时可能需要进行异常处理、连接管理等相关操作,以满足具体的需求。 [2023-10-04 15:10:05 | AI写代码神器 | 1596点数解答]