欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用java下载网络资源

程序员文章站 2022-05-05 20:42:11
...
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileURL = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599655220818&di=f1fa0e2cb095632e16e0c1a8d7470ebf&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F01%2F06%2F01300000329394123030066246677.jpg";
        URL url = new URL(fileURL);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        String fileName = fileURL.substring(fileURL.lastIndexOf(".") - 6);
        resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        InputStream inputStream = urlConnection.getInputStream();
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        outputStream.close();
        inputStream.close();
        urlConnection.disconnect();

    }
相关标签: servlet