把网上图片下载到本地的java工具类

package com.swift;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadPicUtil {

    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    
    public static void downloadPic(String strUrl,String savePath) throws Exception {
        HttpURLConnection conn = null;
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            InputStream is = conn.getInputStream();//连接得到输入流内容
            File file=new File(savePath);
            if(!file.exists()) {//保存文件夹不存在则建立
                file.mkdirs();
            }
            FileOutputStream fos=new FileOutputStream(new File(savePath,strUrl.substring(strUrl.lastIndexOf("/")+1)));//获取网址中的图片名
            int intRead = 0;
            byte[] buf=new byte[1024*2];//生成2K 大小的容器用于接收图片字节流
            while ((intRead = is.read(buf)) != -1) {
                fos.write(buf,0,intRead);//文件输出流到指定路径文件
                fos.flush();
            }
            fos.close();//关闭输出
            if (conn != null) {
                conn.disconnect();//关闭连接
            }
    }
}

 上边这个不好看懂,重写了一个

package com.swift.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

/**
 * Servlet implementation class DownServletYangyan
 */
public class DownServletYangyan extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

        String path=this.getServletContext().getRealPath("download/美女.jpg");//这个是通过项目中的地址得到实际存放在地址
        String mime=this.getServletContext().getMimeType(path);//这个只是知道一下是什么类型,没用
        String filename="美女.jpg";//这个是下载时显示的下载名
        String agent=request.getHeader("User-Agent");
        if(agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }else if(agent.contains("firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        }else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        
        response.setHeader("Content-Disposition", "attachment;filename="+filename);//告诉浏览器用附件法打开
        FileInputStream fis=new FileInputStream(path);
        ServletOutputStream out=response.getOutputStream();//servlet的响应输出流送回
        byte[] buf=new byte[1024];
        int len;
        while((len=fis.read(buf))!=-1) {
            out.write(buf, 0, len);
        }
        fis.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

posted @ 2017-10-03 21:23  Advancing-Swift  阅读(538)  评论(0编辑  收藏  举报