我编写了一个Servlet程序来下载文件。从服务器获得响应后,我打印响应的内容,如下所示:
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.i("THE RESPONSE",(sb.toString()));
但是,打印文件的内容不完整。只打印部分文件。是因为服务器只向我发送部分文件?如果是,那么如何确保我获得完整的文件。
这是我的servlet:
response.setContentType("text/plain");
response.setHeader("Content-Disposition","attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/downloadtest.txt");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
这就是我提出请求的方式:
HttpResponse response = httpClient.execute(getRequest);
要下载的文件大小为208Kb,BYTE_DOWNLOAD的值为1024 * 1024。
如何解决这个问题?