java接收text/event-stream格式数据,并且解决接收HTTPS会不是流式输出问题
前段时间因为要对接语音转文字接口,对方接口输出的是text/event-stream返回,返回的是流式输出,本人在百度找了好久,一直没有找到关于怎么接收流式返回的文章,可能很多人不清楚流式输出指的是什么,流式输出是和对方建立一个长连接,接口方会一直不断的给我们推送数据,而不用等待对方接口完全输出后在把返回值一次性返回。
先贴代码文章来源:https://www.toymoban.com/news/detail-524301.html
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参数。文章来源地址https://www.toymoban.com/news/detail-524301.html
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.设置URL
URL url = new URL(urlStr);
//2.打开URL连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.设置请求方式
conn.setRequestMethod("POST");
//4.设置Content-Type
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//5.设置Accept
conn.setRequestProperty("Accept", "text/event-stream");
//6.设置DoOutput
conn.setDoOutput(true);
//7.设置DoInput
conn.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怎么样返回给前端流式输出有疑问,可以私信问我
到了这里,关于java接收text/event-stream格式数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!