Java企業微信開發_06_素材管理之上傳本地臨時素材文件至微信服務器

1、本節要點

1.臨時素材有效期

media_id是可複用的,同一個media_id可用於消息的屢次發送(3天內有效)html

 

2.上傳文件時的http請求裏都有啥

 

具體原理可參看: 爲何上傳文件的表單須要設置enctype="multipart/form-data" (http://blog.csdn.net/mazhibinit/article/details/49667511java

 

3.上傳本地臨時素材到微信服務器的流程

(1)創建與微信服務器的網絡鏈接json

(2)從鏈接中獲取輸出流(寫入微信服務器的),將本地文件以文件流的形式 寫入輸出流api

(3)從鏈接中獲取輸入流(微信服務器返回的),獲取輸入流中的微信服務器返回的數據(type、media_id、created_at)緩存

(4)上傳完素材就要使用素材了:這時,咱們拿着上一步的media_id,去作發送圖片消息的測試。服務器

 

 

2、代碼實現

1. 微信上傳素材的請求方法

public static String httpRequest(String requestUrl, File file)
/**
     * @desc :微信上傳素材的請求方法
     *  
     * @param requestUrl  微信上傳臨時素材的接口url
     * @param file    要上傳的文件
     * @return String  上傳成功後,微信服務器返回的消息
     */
    public static String httpRequest(String requestUrl, File file) {  
        StringBuffer buffer = new StringBuffer();  
    
        try{
            //1.創建鏈接
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打開連接
            
            //1.1輸入輸出設置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用緩存
            //1.2設置請求頭信息
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            //1.3設置邊界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);

            // 請求正文信息
            // 第一部分:
            //2.將文件頭輸出到微信服務器
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必須多兩道線
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    + "\";filename=\""+ file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 得到輸出流
            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            // 將表頭寫入輸出流中:輸出表頭
            outputStream.write(head);

            //3.將文件正文部分輸出到微信服務器
            // 把文件以流文件的方式 寫入到微信服務器中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            //4.將結尾部分輸出到微信服務器
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後數據分隔線
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();

            
            //5.將微信服務器返回的輸入流轉換成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
            
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            
            bufferedReader.close();  
            inputStreamReader.close();  
            // 釋放資源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

            
        } catch (IOException e) {
            System.out.println("發送POST請求出現異常!" + e);
            e.printStackTrace();
        } 
        return buffer.toString();
    }
View Code

 

2.微信工具類——WeiXinUtil

咱們將1中的微信上傳素材的請求方法封裝到WeiXinUtil.ava中微信

package com.ray.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;


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

import com.ray.pojo.AccessToken;




import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeiXinUtil {

    private static Logger log = LoggerFactory.getLogger(WeiXinUtil.class);  
    //微信的請求url
    //獲取access_token的接口地址(GET) 限200(次/天)  
    public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";  



    /**
     * 1.發起https請求並獲取結果 
     *  
     * @param requestUrl 請求地址 
     * @param requestMethod 請求方式(GET、POST) 
     * @param outputStr 提交的數據 
     * @return JSONObject(經過JSONObject.get(key)的方式獲取json對象的屬性值) 
     */  
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {  
        JSONObject jsonObject = null;  
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 建立SSLContext對象,並使用咱們指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 從上述SSLContext對象中獲得SSLSocketFactory對象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  

            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  

            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 設置請求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  

            if ("GET".equalsIgnoreCase(requestMethod))  
                httpUrlConn.connect();  

            // 當有數據須要提交時  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意編碼格式,防止中文亂碼  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  

            // 將返回的輸入流轉換成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 釋放資源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            log.error("Weixin server connection timed out.");  
        } catch (Exception e) {  
            log.error("https request error:{}", e);  
        }  
        return jsonObject;  
    }  
    /**
     * @desc :微信上傳素材的請求方法
     *  
     * @param requestUrl  微信上傳臨時素材的接口url
     * @param file    要上傳的文件
     * @return String  上傳成功後,微信服務器返回的消息
     */
    public static String httpRequest(String requestUrl, File file) {  
        StringBuffer buffer = new StringBuffer();  
    
        try{
            //1.創建鏈接
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打開連接
            
            //1.1輸入輸出設置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用緩存
            //1.2設置請求頭信息
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            //1.3設置邊界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);

            // 請求正文信息
            // 第一部分:
            //2.將文件頭輸出到微信服務器
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必須多兩道線
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    + "\";filename=\""+ file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 得到輸出流
            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            // 將表頭寫入輸出流中:輸出表頭
            outputStream.write(head);

            //3.將文件正文部分輸出到微信服務器
            // 把文件以流文件的方式 寫入到微信服務器中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            //4.將結尾部分輸出到微信服務器
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後數據分隔線
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();

            
            //5.將微信服務器返回的輸入流轉換成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
            
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            
            bufferedReader.close();  
            inputStreamReader.close();  
            // 釋放資源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

            
        } catch (IOException e) {
            System.out.println("發送POST請求出現異常!" + e);
            e.printStackTrace();
        } 
        return buffer.toString();
    }

    /** 
     * 2.發起http請求獲取返回結果 
     *  
     * @param requestUrl 請求地址 
     * @return 
     */  
    public static String httpRequest(String requestUrl) {  
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  

            httpUrlConn.setDoOutput(false);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  

            httpUrlConn.setRequestMethod("GET");  
            httpUrlConn.connect();  

            // 將返回的輸入流轉換成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 釋放資源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

        } catch (Exception e) {  
        }  
        return buffer.toString();  
    }  


    /** 
     * 3.獲取access_token 
     *  
     * @param appid 憑證 
     * @param appsecret 密鑰 
     * @return 
     */  
    public static AccessToken getAccessToken(String appid, String appsecret) {  
        AccessToken accessToken = null;  

        String requestUrl = access_token_url.replace("{corpId}", appid).replace("{corpsecret}", appsecret);  
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);  
        // 若是請求成功  
        if (null != jsonObject) {  
            try {  
                accessToken = new AccessToken();  
                accessToken.setToken(jsonObject.getString("access_token"));  
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));  
            } catch (JSONException e) {  
                accessToken = null;  
                // 獲取token失敗  
                log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
            }  
        }  
        return accessToken;  
    }  


    /**
     * 3.獲取微信的JSSDK配置信息
     * 方法名:getWxConfig</br>
     * 詳述:獲取微信的配置信息 </br>
     * 開發人員:souvc  </br>
     * 建立時間:2016-1-5  </br>
     * @param request
     * @return 說明返回值含義
     * @throws 說明發生此異常的條件
     */
    public static Map<String, Object> getWxConfig(HttpServletRequest request) {
        Map<String, Object> ret = new HashMap<String, Object>();

        String appId = "wxa0064ea657f80062"; // 必填,公衆號的惟一標識
        String secret = "fcc960840df869ad1a46af7993784917";

        String requestUrl = request.getRequestURL().toString();
        String access_token = "";
        String jsapi_ticket = "";
        String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填,生成簽名的時間戳
        String nonceStr = UUID.randomUUID().toString(); // 必填,生成簽名的隨機串
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId + "&secret=" + secret;
        //使用http請求獲取access_token
        JSONObject json = WeiXinUtil.httpRequest(url, "GET", null);
        System.out.println(" 獲取access_token "+json);
        if (json != null) {
            //要注意,access_token須要緩存
            access_token = json.getString("access_token");
            //根據access_token獲取jsapi_ticket
            url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token + "&type=jsapi";
            json = WeiXinUtil.httpRequest(url, "GET", null);
            System.out.println("jsapi_ticket "+json);
            if (json != null) {
                jsapi_ticket = json.getString("ticket");
            }
        }
        String signature = "";
        // 注意這裏參數名必須所有小寫,且必須有序
        String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr+ "&timestamp=" + timestamp + "&url=" + requestUrl;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(sign.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ret.put("appId", appId);
        ret.put("timestamp", timestamp);
        ret.put("nonceStr", nonceStr);
        ret.put("signature", signature);
        return ret;
    }


    /**
     * 方法名:byteToHex</br>
     * 詳述:字符串加密輔助方法 </br>
     * 開發人員:souvc  </br>
     * 建立時間:2016-1-5  </br>
     * @param hash
     * @return 說明返回值含義
     * @throws 說明發生此異常的條件
     */
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;

    }
}
View Code

 

3.業務類——TempMaterialService

package com.ray.service;

import java.io.File;


import com.ray.util.WeiXinUtil;

import net.sf.json.JSONObject;

/**@desc  : 臨時素材業務類
 * 
 * @author: shirayner
 * @date  : 2017-8-18 下午2:07:25
 */
public class TempMaterialService {
    //上傳臨時素材url
    public static String uploadTempMaterial_url="https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";

    /**
     * @desc :上傳臨時素材
     *  
     * @param accessToken   接口訪問憑證 
     * @param type   媒體文件類型,分別有圖片(image)、語音(voice)、視頻(video),普通文件(file) 
     * @param fileUrl  本地文件的url。例如 "D/1.img"。
     * @return JSONObject   上傳成功後,微信服務器返回的參數,有type、media_id    、created_at
     */
    public JSONObject uploadTempMaterial(String accessToken,String type,String fileUrl){
        //1.建立本地文件
        File file=new File(fileUrl);
        
        //2.拼接請求url
        uploadTempMaterial_url=uploadTempMaterial_url.replace("ACCESS_TOKEN", accessToken)
                .replace("TYPE", type);
        
        //3.調用接口,發送請求,上傳文件到微信服務器
        String result=WeiXinUtil.httpRequest(uploadTempMaterial_url, file);
        
        //4.json字符串轉對象:解析返回值,json反序列化
        result = result.replaceAll("[\\\\]", "");
        System.out.println("result:" + result);
        JSONObject resultJSON = JSONObject.fromObject(result);
        
        //5.返回參數判斷
        if (resultJSON != null) {
            if (resultJSON.get("media_id") != null) {
                System.out.println("上傳" + type + "永久素材成功");
                return resultJSON;
            } else {
                System.out.println("上傳" + type + "永久素材失敗");
            }
        }
        return null;
    }

}
View Code

 

4.測試類——TempMaterialTest

package com.ray.test;

import org.junit.Test;

import com.ray.service.TempMaterialService;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;

/**@desc  : 臨時素材
 * 
 * @author: shirayner
 * @date  : 2017-8-18 下午2:06:10
 */
public class TempMaterialTest {

    @Test
    public void testUploadTempMaterial(){
        //1.初始化參數
        String fileUrl="D:/renwu1.jpg";
        String type="image";
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.contactsSecret).getToken();
        //2.調用業務類,上傳臨時素材
        TempMaterialService tms=new TempMaterialService();
        tms.uploadTempMaterial(accessToken, type, fileUrl);
        
        
        
    }
}
View Code

這時在控制檯上會打印出微信服務器返回的media_id,咱們拿着這個media_id去完成發送消息之發送圖片消息的測試,參見  Java企業微信開發_05_消息推送之發送消息(主動)網絡

 

5.測試類——SendMessageTest

package com.ray.test;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;


import com.ray.pojo.message.send.Article;
import com.ray.pojo.message.send.FileMessage;
import com.ray.pojo.message.send.ImgMessage;
import com.ray.pojo.message.send.Media;
import com.ray.pojo.message.send.News;
import com.ray.pojo.message.send.NewsMessage;
import com.ray.pojo.message.send.Text;
import com.ray.pojo.message.send.TextMessage;
import com.ray.pojo.message.send.Textcard;
import com.ray.pojo.message.send.TextcardMessage;
import com.ray.pojo.message.send.Video;
import com.ray.pojo.message.send.VideoMessage;
import com.ray.pojo.message.send.VoiceMessage;
import com.ray.service.SendMessageService;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;

/**@desc  : 消息推送之發送消息
 * 
 * @author: shirayner
 * @date  : 2017-8-18 上午10:04:55
 */
public class SendMessageTest {

    //1.發送文本消息
    @Test
    public void testSendTextMessage(){
        //0.設置消息內容
        String content="rayge,你好!你的快遞已到,請攜帶工卡前往郵件中心領取。\n出發前可查看" +
                "<a href=\"http://work.weixin.qq.com\">郵件中心視頻實況" +
                "</a>,聰明避開排隊。";

        //1.建立文本消息對象
        TextMessage message=new TextMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("text");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Text text=new Text();
        text.setContent(content);
        message.setText(text);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }

    //2.發送文本卡片消息
    @Test
    public void testSendTextcardMessage(){
        //0.設置消息內容
        String title="代辦事宜";
        String description="<div class=\"gray\">2017年8月18日</div> <div class=\"normal\">" +
                "恭喜你抽中iPhone 7一臺,領獎碼:xxxx</div><div class=\"highlight\">" +
                "請於2017年10月10日前聯繫行政同事領取</div>";
        String url="http://www.cnblogs.com/shirui/p/7297872.html";

        //1.建立文本卡片消息對象
        TextcardMessage message=new TextcardMessage();
        //1.1非必需
        message.setTouser("shirui");  //不區分大小寫
        //message.setToparty("1");
        //message.setTotag(totag);
        //message.setSafe(0);

        //1.2必需
        message.setMsgtype("textcard");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Textcard textcard=new Textcard();
        textcard.setTitle(title);
        textcard.setDescription(description);
        textcard.setUrl(url);
        message.setTextcard(textcard);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }

    //3.發送圖片消息---無效的media_id
    @Test
    public void testSendImgMessage(){
        //0.設置消息內容
        //String media_id="MEDIA_ID";
        String media_id="3oKgxI6C_Z_8gPr5a1ORIhYTLlMJnoMWbrRIrip2p6oQ";
        //1.建立圖片消息對象
        ImgMessage message=new ImgMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("image");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Media image=new Media();
        image.setMedia_id(media_id);
        message.setImage(image);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }


    //4.發送語音消息---無效的media_id
    @Test
    public void testSendVoiceMessage(){
        //0.設置消息內容
        String media_id="MEDIA_ID";
        //1.建立語音消息對象
        VoiceMessage message=new VoiceMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("image");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Media voice=new Media();
        voice.setMedia_id(media_id);
        message.setVoice(voice);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }

    //5.發送視頻消息
    @Test
    public void testSendVideoMessage(){
        //0.設置消息內容
        String media_id="MEDIA_ID";
        String title="視頻示例";
        String description="好看的視頻";


        //1.建立視頻消息對象
        VideoMessage message=new VideoMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //message.setToparty("1");
        //message.setTotag(totag);
        //message.setSafe(0);

        //1.2必需
        message.setMsgtype("video");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Video video=new Video();
        video.setMedia_id(media_id);
        video.setTitle(title);
        video.setDescription(description);
        message.setVideo(video);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }

    //6.發送文件消息
    @Test
    public void testSendFileMessage(){
        //0.設置消息內容
        String media_id="MEDIA_ID";

        //1.建立文件對象
        FileMessage message=new FileMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("file");
        message.setAgentid(WeiXinParamesUtil.agentId);

        Media file=new Media();
        file.setMedia_id(media_id);
        message.setFile(file);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }

    //7.發送圖文消息
    @Test
    public void testSendNewsMessage(){

        //1.建立圖文消息對象
        NewsMessage message=new NewsMessage();
        //1.1非必需
        message.setTouser("@all");  //不區分大小寫
        //textMessage.setToparty("1");
        //txtMsg.setTotag(totag);
        //txtMsg.setSafe(0);

        //1.2必需
        message.setMsgtype("news");
        message.setAgentid(WeiXinParamesUtil.agentId);
        //設置圖文消息
        Article article1=new  Article();
        article1.setTitle("青年文摘");
        article1.setDescription("這是一個很特別的描述");
        article1.setPicurl("http://img.hb.aicdn.com/41db5196f17008a1994e978603c18dfaaa4b703f465a9-DcgZvI_fw658");
        article1.setUrl("http://www.cnblogs.com/shirui/p/7297872.html");
        
        List<Article>  articles=new ArrayList<Article>();
        articles.add(article1);
        
        News news=new News();
        news.setArticles(articles);
        message.setNews(news);

        //2.獲取access_token:根據企業id和通信錄密鑰獲取access_token,並拼接請求url
        String accessToken= WeiXinUtil.getAccessToken(WeiXinParamesUtil.corpId, WeiXinParamesUtil.agentSecret).getToken();
        System.out.println("accessToken:"+accessToken);

        //3.發送消息:調用業務類,發送消息
        SendMessageService sms=new SendMessageService();
        sms.sendMessage(accessToken, message);

    }




}
View Code

運行testSendImgMessage()方法,打開企業微信,發現真的發送了一張圖片給用戶。微信開發

 

 

 

參考文章:http://blog.csdn.net/u013791374/article/details/53258275app

相關文章
相關標籤/搜索