送信要求下リンク画像をローカルにダウンロード

18198 ワード

需要シーン
リンクは以下の通りです.http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83erZB34ia5VF1XkR7gmbcFvj9ibn1dhb67woDjLIjS7q5utvyExLsdyia7rrsZqIXTccnQpB4ZQSicgPiag/0 发送请求下链接图片下载到本地_第1张图片この場合、送信要求によって画像をローカルにダウンロードする必要があります.
MountFileコード
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.**.pojo.MountInfo;

public class MountFile {
    private static final Logger logger = LoggerFactory.getLogger(MountFile.class);

    //      
    private final static String url_suffix = "data/image/";

    public static String getRootPath() {
        return rootPath;
    }

    public static String getQrRootPath(){
        return qrRootPath;
    }

    public static String getQrUrlSuffix(){
        return qr_url_suffix;
    }

    public static void mkDir(String filePath) {
        File f;
        f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
    }

    /**
     *        
     * 
     * @return
     */
    public static String getDir() {
        Calendar cl = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = dateFormat.format(cl.getTime());
        String hour = cl.get(Calendar.HOUR) < 10 ? "0" + cl.get(Calendar.HOUR) : String.valueOf(cl.get(Calendar.HOUR));
        String minute = cl.get(Calendar.MINUTE) < 10 ? "0" + cl.get(Calendar.MINUTE) : String.valueOf(cl
                .get(Calendar.MINUTE));
        String dir = date + "/" + hour + "/" + minute + "/";
        return dir;
    }

    public static String getFileName(String fileType) {
        return FileFactory.getInstance().getRandName() + fileType;
    }

    public static MountInfo getMountFullPath(String fileExt) {
        String dirPath = getDir();
        String fileName = getFileName(fileExt);
        String imgUrl = "";
        //     
        mkDir(getRootPath() + dirPath);
        String fullName = getRootPath() + dirPath + fileName;
        imgUrl = url_suffix + dirPath + fileName;
        if ("".equals(imgUrl)) {
            logger.info("upload img failed");
        }
        MountInfo info = new MountInfo();
        info.setFilePath(fullName);
        info.setRelativeUrl(imgUrl);
        String httpUrl = "https://img.**.com" + imgUrl;
        info.setUrl(httpUrl);
        return info;
    }
}

FileFactoryコード
import java.util.Calendar;
import java.util.Random;

import org.apache.commons.lang.RandomStringUtils;

public class FileFactory {
    private static FileFactory instance;

    private static String seed[] = { "a", "b", "c", "d",   "e", "f", "g", "h",  "i", "j", "k", "l",   "m", "n", "o", "p",  "q","r","s","t", "u","v","w","x"  };


    private Random rand = new Random();

    static {
        instance = new FileFactory();
    }

    public static FileFactory getInstance() {

        return instance;
    }


    public FileFactory() {
        for (int i = 0; i < seed.length; i++) {
        }
    }

    public  String getRandName() {
        int qid = rand.nextInt(seed.length);
        Calendar cl = Calendar.getInstance();
        String hour = cl.get(Calendar.HOUR) < 10 ? "0" + cl.get(Calendar.HOUR): String.valueOf(cl.get(Calendar.HOUR));
        String minute = cl.get(Calendar.MINUTE) < 10 ? "0"+ cl.get(Calendar.MINUTE) : String.valueOf(cl.get(Calendar.MINUTE));
        String suffix = RandomStringUtils.randomAlphanumeric(4);
        return  suffix+"_"+seed[qid] +seed[cl.get(Calendar.HOUR)]+seed[cl.get(Calendar.MINUTE) % 24]+qid+hour+minute ;
    }

    public String getPathByTime() {
        return null;
    }
}

MountInfoクラスのコードpojo
import com.alibaba.fastjson.JSONObject;
public class MountInfo {
    private String filePath;//      
    private String relativeUrl;
    private String url;//      

    public String getFilePath() {
        return filePath;
    }
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public String getRelativeUrl() {
        return relativeUrl;
    }
    public void setRelativeUrl(String relativeUrl) {
        this.relativeUrl = relativeUrl;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    @Override
    public String toString() {
        String mountInfoStr = JSONObject.toJSONString(this);
        return mountInfoStr;
    }

}

httpDownLoadImageクラスのコード
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.**.pojo.MountInfo;
import com.***.util.card.MountFile;

public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     *     
     * @param url
     * @param path
     */
    @SuppressWarnings("resource")
    public static MountInfo httpDownLoadImage(String url) {
        MountInfo mountInfo = new MountInfo();
        String fullFilePath = "";
        //            (        )
        String fileExt = getFileexpandedName("jpg");
        //  mediaId     
        mountInfo = MountFile.getMountFullPath(fileExt);
        fullFilePath = mountInfo.getFilePath();
        InputStream inputStream = getInputStream(url);
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileoutputStream = null;
        try {
            fileoutputStream = new FileOutputStream(new File(fullFilePath));
            while ((len = inputStream.read(data)) != -1) {
                fileoutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mountInfo;
    }

    /**
    *         , InputStream    
    * @return
    */
    public static InputStream getInputStream(String urlPath) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlPath);
            if (url != null) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                //           
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                //       http     GET    
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    //             
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        else {
            fileEndWitsh = ".jpg";
        }
        logger.info("fileEndWitsh={}", fileEndWitsh);
        return fileEndWitsh;
    }

    public static void main(String[] args) {
    //               
        MountInfo httpDownLoadImage = ImageUtil.httpDownLoadImage("http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83erZB34ia5VF1XkR7gmbcFvj9ibn1dhb67woDjLIjS7q5utvyExLsdyia7rrsZqIXTccnQpB4ZQSicgPiag/0");
        System.out.println(httpDownLoadImage.toString());
    }

}