用JAVA写一个通过GET请求获取EventStream数据
时间: 2024-05-02 13:21:23 浏览: 19
以下是使用Java代码从EventStream获取数据的示例:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EventStreamExample {
public static void main(String[] args) throws Exception {
// 创建URL对象
URL url = new URL("http://example.com/events");
// 创建HttpURLConnection对象并设置请求属性
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "text/event-stream");
// 读取服务器响应流
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 关闭连接和读取器
reader.close();
connection.disconnect();
}
}
```
在此示例中,我们创建了一个URL对象来表示我们要请求的EventStream的URL。然后我们创建了一个HttpURLConnection对象并设置请求属性,包括请求方法和Accept头,以指示我们要接收的数据类型。最后,我们使用BufferedReader从服务器响应流中读取数据,并将每一行打印到控制台上。最后,我们关闭连接和读取器。
请注意,这只是一个示例代码,您需要根据您的具体情况进行修改。例如,您可能需要处理错误情况和超时。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![chm](https://img-home.csdnimg.cn/images/20210720083646.png)
![chm](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)