java接收text/event-stream格式数据,并且解决接收HTTPS会不是流式输出问题

前段时间因为要对接语音转文字接口,对方接口输出的是text/event-stream返回,返回的是流式输出,本人在百度找了好久,一直没有找到关于怎么接收流式返回的文章,可能很多人不清楚流式输出指的是什么,流式输出是和对方建立一个长连接,接口方会一直不断的给我们推送数据,而不用等待对方接口完全输出后在把返回值一次性返回。

先贴代码

get请求

public String getEventStream(String urlStr, HttpServletResponse response) {long statr = System.currentTimeMillis();log.info("开始请求接口url:{}", urlStr);InputStream is = null;StringBuffer bu = new StringBuffer();try {URL url = new URL(urlStr);URLConnection conn = url.openConnection();is = conn.getInputStream();byte[] b = new byte[1024];int len = -1;long end = System.currentTimeMillis();log.info("接口url:{},请求开始流式输出{}", urlStr, end - statr);while ((len = is.read(b)) != -1) {String line = new String(b, 0, len, "utf-8");// 处理 event stream 数据response.getWriter().write(line);response.getWriter().flush();bu.append(line);}} catch (IOException e) {log.error("请求模型接口异常", e);throw new BusinessException(ResponseCode.TOPIC_INITIATION_FAILED);} finally {if (!Objects.isNull(is)) {try {//12.关闭输入流is.close();} catch (IOException e) {e.printStackTrace();}}}return bu.toString();}

这里的urlStr参数是url加参数,示例:https://baidu.com?text=12345678
response是因为我需要同样用流式输出文字给前端,如果你不需要返回给前端,可以不用response参数。

post请求

public String postEventStream(String urlStr, String json, HttpServletResponse response) {long statr = System.currentTimeMillis();log.info("开始请求接口url:{},请求参数{}", urlStr,json);InputStream is = null;//11.读取输入流中的返回值StringBuffer bu = new StringBuffer();try {//1.设置URLURL url = new URL(urlStr);//2.打开URL连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//3.设置请求方式conn.setRequestMethod("POST");//4.设置Content-Typeconn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//5.设置Acceptconn.setRequestProperty("Accept", "text/event-stream");//6.设置DoOutputconn.setDoOutput(true);//7.设置DoInputconn.setDoInput(true);//8.获取输出流OutputStream os = conn.getOutputStream();//9.写入参数(json格式)os.write(json.getBytes("utf-8"));os.flush();os.close();//10.获取输入流is = conn.getInputStream();byte[] bytes = new byte[1024];int len = 0;long end = System.currentTimeMillis();log.info("接口url:{},请求参数{},请求开始流式输出{}", urlStr,json, end - statr);while ((len = is.read(bytes)) != -1) {String line = new String(bytes, 0, len, "utf-8");response.getWriter().write(line);response.getWriter().flush();bu.append(line);}} catch (IOException e) {log.error("请求模型接口异常", e);throw new BusinessException(ResponseCode.TOPIC_INITIATION_FAILED);} finally {if (!Objects.isNull(is)) {try {//12.关闭输入流is.close();} catch (IOException e) {e.printStackTrace();}}}return bu.toString();}

第一次写文章,表达不好请谅解,这里使用的jdk版本是1.8,如果对于springboot怎么样返回给前端流式输出有疑问,可以私信问我