在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ 關(guān)于流式讀取http body體內(nèi)容

關(guān)于流式讀取http body體內(nèi)容

如果采用octet-stream方式用http把一個很大的文件放入body體里傳輸。在服務(wù)端這種使用流的方式接收,時實時接收的嗎?

public void downLoad(String remoteFileName, String localFileName) {
2 DefaultHttpClient httpClient = new DefaultHttpClient();
3 OutputStream out = null;
4 InputStream in = null;
5
6 try {
7 HttpGet httpGet = new HttpGet(URL_STR);
8
9 httpGet.addHeader("userName", userName);
10 httpGet.addHeader("passwd", passwd);
11 httpGet.addHeader("fileName", remoteFileName);
12
13 HttpResponse httpResponse = httpClient.execute(httpGet);
14 HttpEntity entity = httpResponse.getEntity(); // 獲取流實體
15 in = entity.getContent(); // 獲取流實體內(nèi)容
16
17 long length = entity.getContentLength();
18 if (length <= 0) {
19 System.out.println("下載文件不存在!");
20 return;
21 }
22
23 System.out.println("The response value of token:" + httpResponse.getFirstHeader("token"));
24
25 File file = new File(localFileName);
26 if(!file.exists()){
27 file.createNewFile();
28 }
29
30 out = new FileOutputStream(file);
31 byte[] buffer = new byte[4096];
32 int readLength = 0;
33 while ((readLength=in.read(buffer)) > 0) { // 循環(huán)讀取流內(nèi)容,這里是客戶端一邊傳輸,服務(wù)端這里邊讀嗎?如果是這樣,如果文件很大,是不是會在這里循環(huán)很久。另外,這里while怎么能保證讀取的是一個完整的文件?因為網(wǎng)絡(luò)是斷斷續(xù)續(xù)的。這個異步的過程究竟是怎么樣的?
34 byte[] bytes = new byte[readLength];
35 System.arraycopy(buffer, 0, bytes, 0, readLength);
36 out.write(bytes);
37 }
38
39 out.flush();
40
41 } catch (IOException e) {
42 e.printStackTrace();
43 } catch (Exception e) {
44 e.printStackTrace();
45 }finally{
46 try {
47 if(in != null){
48 in.close();
49 }
50 } catch (IOException e) {
51 e.printStackTrace();
52 }
53
54 try {
55 if(out != null){
56 out.close();
57 }
58 } catch (IOException e) {
59 e.printStackTrace();
60 }
61 }
62 }

回答
編輯回答
貓小柒

完全可以,參閱HttpServletRequest.getInputStream()。

Servlet 3.1的話,還可以實時異步處理。

2017年4月14日 11:19