我有一个要求,我必须创建一个流休息api来读取文件。我们正在构建类似于 cat linux命令的东西。
因此,如果用户键入 ccat filename |然后我们必须保持流打开并以256字节的块读出内容,并等待资源从客户端关闭。
我创建了一个POC。其余的api代码看起来像这样 -
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@RequestMapping(method = RequestMethod.GET, value = "stream")
public void hello(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws InterruptedException {
String content = "This is the text content";
ServletOutputStream outputStream = null;
try {
for(int i=0;i<100;i++){
content = content + i;
final byte[] bytes = content.getBytes();
outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setStatus(200);
outputStream.write(bytes);
Thread.sleep(1000l);
outputStream.flush();
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
客户端代码如下 -
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:6868/api/stream");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn);
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这工作正常,但问题是它不是一次性写入字节块,而是整个内容。我正在调用flush()所以我希望它会在每次调用flush()时将块发送到客户端,但这似乎并没有发生。它在调用close()后发送给客户端。我该如何解决这个问题?