android客户端从服务器端下载文件,服务端返回文件流

服务端 strtus:
/**  * 文件下载 : 返回文件流  * @param mapping  * @param actionForm  * @param request  * @param response  * @return  * @throws Exception  */ public ActionForward fileUpload(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.debug("fileUpload()"); RequestMap params = WebUtil.getQueryMap(request); String file_key = (String)params.get("filekey", ""); if(file_key != null && !"".equals(file_key)){ NewsPaperManager service = NewsPaperManager.getInstance(); String file_path = service.getFilePath(file_key); if(file_path != null && !"".equals(file_path)){ File file = new File(file_path); if(file.exists()){ InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); // 设置response的Header response.setHeader("Content-Type", "application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + file.getName()); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = response.getOutputStream(); toClient.write(buffer); toClient.flush(); toClient.close(); } } } return null; }


android客户端:
    public byte[] getImage(String path) throws Exception { URL url = new URL("http://120.197.230.53:9902/kuchuan_api/newspaper.do?method=fileUpload&filekey=2LM7vAcHt8iFX2ABTXZT"); HttpURLConnection conn = (HttpURLConnection)url.openConnection();//基于HTTP协议的连接对象 conn.setConnectTimeout(5000);//请求超时时间 5s conn.setRequestMethod("GET");//请求方式 Log.i("ResponseCode", "prepare"); Log.i("ResponseCode", conn.getResponseCode()+""); if(conn.getResponseCode() == 200){//响应码==200 请求成功 InputStream inputStream = conn.getInputStream();//得到输入流 Log.i("ResponseCode", inputStream.toString().length()+""); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; Log.i("ResponseCode", "inputStream.read(buffer) :"+inputStream.read(buffer)+""); while((len = inputStream.read(buffer)) != -1){ arrayOutputStream.write( buffer, 0, len); Log.i("ResponseCode", "buffer.length :"+buffer.length+"  " + len); } inputStream.close(); arrayOutputStream.close(); Log.i("ResponseCode", "arrayOutputStream.toByteArray().length :"+arrayOutputStream.toByteArray().length+""); } return null; }    

更多相关文章

  1. android 随手记之文件+参数上传请求
  2. 清单文件Manifest中的android:name
  3. Android之录制视频文件
  4. 31、android打开文件夹并列出里面的文件
  5. Android中上传图片到服务端C#接收图
  6. Android中,把XML文件转换成Object对象的方法
  7. Android 读取doc文件
  8. Android中通过资源文件获取drawable的几种方法

随机推荐

  1. Android(安卓)Tab 选项卡的简单实现
  2. Android的多媒体框架OpenCore介绍
  3. 为数不多的人知道的AndroidStudio快捷键(
  4. Android百度地图(四):百度地图运动轨迹纠
  5. 获取Android(安卓)SDK 源代码并在Eclipse
  6. Android(安卓)获取USB扫描枪简易封装
  7. Android的多媒体框架Opencore代码阅读
  8. android中下载文件到sdcard和进度条小结
  9. Android重温
  10. 腾讯Android面经