最近做即时通讯,要在openfire上开发插件保存离线文件。我的思路是客户端登陆后向服务器提交GET请求,然后服务器通过OutputStream将文件输出。由于可能有多个离线文件,所以我打算循环输出多个outputstream。但是客户端得到的只是第一个OutputStream。请问怎么解决?
服务器端代码:
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is uploadservlet");
if(req.getParameter("state").equals("online")&&req.getParameter("userTo")!=null){
List<OfflineFile> filelist = dboperator.getOfflineFile(req.getParameter("userTo"));
Iterator<OfflineFile> iterator = filelist.iterator();
OfflineFile offlinefile;
while(iterator.hasNext())
{
offlinefile = iterator.next();
File dfile = new File(offlinefile.getFilepath());
//得到输入流
FileInputStream in = new FileInputStream(dfile);
//获取文件名字,并对其进行编码,如果不这样会出现中文乱码。
String filename = dfile.getName();
filename = new String(filename.getBytes(),"iso8859-1");
//文件的发送者
String userFrom = new String(offlinefile.getUserFrom().getBytes(),"iso8859-1");
System.out.println(userFrom);
//通过response对象获得输出流
OutputStream out = response.getOutputStream();
//
response.setContentType("Application/Octet-stream;charset=utf-8");
// 下载文件的名字和发送者
response.addHeader("Content-Disposition", "attachment; filename="+filename);
response.addHeader("userfrom", userFrom);
response.setContentLength((int) dfile.length());
byte[] bs =new byte[1024];
int len = 0;
while((len =in.read(bs))!=-1){
out.write(bs);
}
// 最后是流的关闭。
out.close();
in.close();
}
}
}
客户端代码:
private static List<InputStream> islist;
`
public static InputStream getInputstream()
{
islist = new ArrayList<InputStream>();
InputStream inputstream=null;
HttpURLConnection urlconnection=null;
try {
String urlpath="http://chen-pc:9090/plugins/upload/upload?state=online&userTo=hehe@chen-pc";
String urlcn=URLEncoder.encode("刘德华_冰雨.mp3","UTF-8");
System.out.println(urlpath+urlcn);
URL url=new URL(urlpath);
urlconnection=(HttpURLConnection)url.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
urlconnection.setConnectTimeout(6000);//设置超时时间
urlconnection.setDoInput(true);
urlconnection.setRequestMethod("GET");//设置GET请求方式
System.out.println(new String(urlconnection.getHeaderField("Content-Disposition").getBytes("iso8859-1"),"gb2312"));
System.out.println(new String(urlconnection.getHeaderField("userfrom").getBytes("iso8859-1"),"gb2312"));
int responsecode=urlconnection.getResponseCode();
if(responsecode==200)
{
inputstream=urlconnection.getInputStream();//获得输入流
islist.add(inputstream);
while(inputstream!=null)
{
inputstream=urlconnection.getInputStream();//获得输入流
if(inputstream!=null){
islist.add(inputstream);
}
}
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return islist.get(1);
}