参考别的前辈的代码,忘记在哪里看的了
InputStream is = null;
try {
//1.设置URL
URL url = new URL("http://.../chat");
//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(new Gson().toJson(aiAskBean).getBytes("utf-8"));
os.flush();
os.close();
//10.获取输入流
is = conn.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
String line = new String(bytes, 0, len, "utf-8");
//line就是每行的数据了,也就是“逐句”
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (!Objects.isNull(is)) {
try {
//12.关闭输入流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}