All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.xiaoyuge5201.weixin.WeiXinGetMediaUtil Maven / Gradle / Ivy

There is a newer version: 1.3.5
Show newest version
package com.github.xiaoyuge5201.weixin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author xiaoyuge
 * 下载media素材
 */
public class WeiXinGetMediaUtil {

    private static Logger log = LoggerFactory.getLogger(WeiXinGetMediaUtil.class);

    /**
     * 下载临时素材  返回素材下载路径
     *
     * @param fileDir 文件存儲路徑
     * @param url     素材地址
     * @param type    類型
     * @return 結果
     * @throws IOException
     */
    public static String getMedia(String fileDir, String url, String mediaId, String type) {
        String filePath = "";
        InputStream is = getInputStream(url);
        if (is == null) {
            log.info("文件路径无效");
        }
        byte[] data = new byte[1024];
        int len = 0;
        OutputStream fileOutputStream = null;
        try {
            File path = new File(fileDir);
            if (!path.exists()) {
                path.mkdirs();
            }

            filePath = fileDir + mediaId + type;
            fileOutputStream = new FileOutputStream(filePath);
            while ((len = is.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
        } catch (Exception e) {
            log.error("信息:" + e.toString(), e);
        } finally {
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
                is.close();
            } catch (IOException e) {
                log.error("信息:" + e.toString(), e);
            }
        }
        return "?name=" + mediaId + type;
    }

    /**
     * 將鏈接
     *
     * @param url
     * @return
     */
    private static InputStream getInputStream(String url) {
        InputStream is = null;
        URL urlGet;
        try {
            urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            http.connect();
            // 获取文件转化为byte流
            is = http.getInputStream();
        } catch (Exception e) {
            log.error("信息:" + e.toString(), e);
        } finally {
        }
        return is;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy