MessageUtil.java 7.38 KB
package com.server.utils.weixin;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.utils.Charsets;
import com.jfinal.weixin.sdk.utils.IOUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 公众号发送图片等
 * Created by dell on 2018/2/28.
 */
public class MessageUtil {
    private static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
    private static String customMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
    //素材上传地址
    private static String MEDIA_UPLOADURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=";

    public MessageUtil() {
    }


    private static Map<String,Object> sendMsg(Map<String, Object> message,String accessToken) {
        String jsonResult = HttpURLUtil.post(customMessageUrl + accessToken, JsonUtils.toJson(message));
        Map resultMap = (Map) JSON.parseObject(jsonResult, Map.class);
//        Number number = (Number)resultMap.get("errcode");
//        Integer errorCode = (number == null?null:Integer.valueOf(number.intValue()));
//        if(errorCode == null || errorCode.intValue() == 0){
//            return resultMap;
//        }else{
//            logger.error("MessageUtil.sendMsg==="+jsonResult+";message="+ReturnCode.get(errorCode));
//            return resultMap;
//        }
        return resultMap;
    }

    /**
     * 发送文本消息
     * @param openId
     * @param text
     * @param accessToken
     * @return
     */
    public static Map<String,Object> sendText(String openId, String text,String accessToken) {
        HashMap json = new HashMap();
        json.put("touser", openId);
        json.put("msgtype", "text");
        HashMap textObj = new HashMap();
        textObj.put("content", text);
        json.put("text", textObj);
        return sendMsg(json,accessToken);
    }


    /**
     * 发送图片消息
     * @param openId
     * @param media_id
     * @param accessToken
     * @return
     */
    public static Map<String,Object> sendImage(String openId, String media_id,String accessToken) {
        HashMap json = new HashMap();
        json.put("touser", openId);
        json.put("msgtype", "image");
        HashMap image = new HashMap();
        image.put("media_id", media_id);
        json.put("image", image);
        return sendMsg(json,accessToken);
    }


    /**
     * 上传临时素材库
     * @param accessToken
     * @param fileUrl
     * @return
     */
    public static Map<String,Object> mediaUploadImageMedia(String accessToken,String fileUrl) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        String url = MEDIA_UPLOADURL + accessToken + "&type=image";
        String jsonStr = null;
        try {
            jsonStr = uploadMedia(url, fileUrl, (String)null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ApiResult apiResult = new ApiResult(jsonStr);
        resultMap.put("jsonStr",jsonStr);
        if(apiResult.isSucceed()){
            resultMap.put("mediaId",apiResult.get("media_id"));
        }else{
            resultMap.put("mediaId","");
        }
        return resultMap;
    }

    protected static String uploadMedia(String url, String fileUrl,String params) throws IOException {
        URL urlGet = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)urlGet.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        conn.setRequestProperty("Charsert", "UTF-8");
        String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        StringBuilder mediaData = new StringBuilder();
        mediaData.append("--").append(BOUNDARY).append("\r\n");
        mediaData.append("Content-Disposition: form-data;name=\"media\";filename=\"" + new File(fileUrl).getName()+ "\"\r\n");
        mediaData.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] mediaDatas = mediaData.toString().getBytes();
        out.write(mediaDatas);
        out.write(downLoadFromUrl(fileUrl));
        out.write("\r\n".getBytes());
        if(StrKit.notBlank(params)) {
            StringBuilder end_data = new StringBuilder();
            end_data.append("--").append(BOUNDARY).append("\r\n");
            end_data.append("Content-Disposition: form-data;name=\"description\";");
            byte[] in = end_data.toString().getBytes();
            out.write(in);
            out.write(params.getBytes(Charsets.UTF_8));
        }

        byte[] end_data1 = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(end_data1);
        out.flush();
        IOUtils.closeQuietly(out);
        InputStream in1 = conn.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in1, Charsets.UTF_8));
        String valueString = null;
        StringBuffer bufferRes = null;
        bufferRes = new StringBuffer();

        while((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }

        IOUtils.closeQuietly(in1);
        if(conn != null) {
            conn.disconnect();
        }

        return bufferRes.toString();
    }

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @throws IOException
     */
    public static byte[]  downLoadFromUrl(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

//        //文件保存位置
//        File saveDir = new File(savePath);
//        if(!saveDir.exists()){
//            saveDir.mkdir();
//        }
//        File file = new File(saveDir+File.separator+fileName);
//        FileOutputStream fos = new FileOutputStream(file);
//        fos.write(getData);
//        if(fos!=null){
//            fos.close();
//        }
//        if(inputStream!=null){
//            inputStream.close();
//        }
        return getData;

    }
    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}