关于扫描二维码下载app功能实现方法

 

功能实现思路:

   Androidapk的下载本质上就是文件的下载,所以我们只需要在后台提供一个下载的方法,就能是实现apk的下载。

   在实现后台代码以后,我们生成一个url下载地址,进入http://cli.im/网站,按网站提示操作,这个网站会免费为我们生成一个二维码提供我们使用。

   扫描二维码,测试是否可以下载,测试成功就表示扫描二维码下载app功能实现。如果不成功,问题可能出现在后台代码,检查下代码是否有误,文件路径是否存在,apk文件是否在正确的路径下,是否配置好<servlet> <servlet-mapping>

 

后台代码Demo:

/**

 *Servlet implementation class DownloadServlet

 */

//@WebServlet("/downloadServlet.do")

public class DownloadServlet extendsHttpServlet {

    privatestatic final long serialVersionUID = 1L;

      

   public DownloadServlet() {

       super();

    }

 

    protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

    Stringpath=getServletContext().getRealPath("/")+"app/";

    Stringfilename=request.getParameter("filename");

    Filefile=new File(path+filename);

    if(file.exists()){

       //设置相应类型

      

    //设置相应类型application/octet-stream

    response.setContentType("application/x-msdownload");

    //设置头信息

    response.setHeader("Content-Disposition","attachment;filename=\"" + filename + "\"");

    InputStreaminputStream = new FileInputStream(file);

    ServletOutputStreamouputStream = response.getOutputStream();

    byteb[] = new byte[1024];

    intn ;

    while((n= inputStream.read(b)) != -1){

       ouputStream.write(b,0,n);

    }

    //关闭流、释放资源

    ouputStream.close();

    inputStream.close();

       }else{

           request.setAttribute("errorResult","文件不存在下载失败!");

           RequestDispatcherdispatcher=request.getRequestDispatcher("index.jsp");

           dispatcher.forward(request,response);

       }

   

    }

    protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {

       doGet(request,response);

    }

 

}

 

该方法存在异常:没有对IO异常进行处理,解决方法后期可以加入断点续传,app不建议这么做,原因是没有那家app提供商会这样出处理,都是重新下载(因为移动端争取的是流量,在不影响使用的情况下,建议采用重新下载的方式处理异常)。所以建议写一个jsp或 html文件在下载失败的时候,给用户友好提示,让其重新下载。