1. 程式人生 > >java公眾號上傳素材及傳送圖文訊息實現

java公眾號上傳素材及傳送圖文訊息實現

微信公眾號先上傳素材,再推送訊息java程式碼實現:

首先公眾號的圖文訊息是可以登入公眾號,然後去管理--素材管理  下面去手動新增圖文,圖片,視訊,音樂素材的.這樣新增的素材屬於永久素材.

用java程式碼實現的時候,很多人報錯無效的media_id, 或無效的thumb_media_id,那是因為你上傳的素材是臨時的,換成永久id就可以了.

以下是我的幾個親測可用的Test.  具體的需求請參考官方文件 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1481187827_i0l21

1.獲取素材列表

package weixin.tuwen;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import weixin.tuwen.pojo.Material;
import weixin.util.WX_HttpsUtil;
import weixin.util.WX_TokenUtil;
import com.alibaba.fastjson.JSONObject;
import com.qs.util.HttpsPostUtil;
import com.qs.util.httpspost.HttpsUtil;

public class TestGetSucaiList {

	/**
	 * 獲取永久素材列表(根據分類)
	 * 圖片(image)、視訊(video)、語音 (voice)、圖文(news)
	 * 引數:type   offset    count
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 */
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
		String access_token = WX_TokenUtil.getWXToken().getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+access_token;
		//POST請求傳送的json引數
		Material m = new Material();
		m.setType("news");
		m.setOffset(0);
		m.setCount(10);
		JSONObject json = (JSONObject) JSONObject.toJSON(m);
		String str = json.toString();
		System.out.println(str);
//		Map<String,String> createMap = new HashMap<String,String>();  
//		createMap.put("type","image");  
//		createMap.put("offset","0");  
//		createMap.put("count","1");
		byte[] result = HttpsUtil.post(url, str, "utf-8");
		String strs = new String(result);
		System.out.println(strs);
	}

}

2.上傳音樂素材到公眾號  (有需要上傳圖片的,請自行把引數替換掉)

package weixin.tuwen;

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.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

import weixin.util.WX_TokenUtil;

public class UploadSucai {

	/**
	 * @param args
	 * 上傳音樂到公眾號
	 * 請求地址(post):https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
	 */
	public static void main(String[] args) {
		String access_token = WX_TokenUtil.getWXToken().getAccessToken();
		File file = new File("C:/Users/v_yiqqin/Music/asdasd.mp3");
		uploadPermanentMedia2(access_token,file,"測試標題","測試描述");
		
	}
	
	
	/** 
     * 這裡說下,在上傳視訊素材的時候,微信說不超過20M,我試了下,超過10M調通的可能性都比較小,建議大家上傳視訊素材的大小小於10M比交好 
     * @param accessToken 
     * @param file  上傳的檔案 
     * @param title  上傳型別為video的引數 
     * @param introduction 上傳型別為video的引數 
     */  
    public static void uploadPermanentMedia2(String accessToken,
            File file,String title,String introduction) {
        try {  
              
            //這塊是用來處理如果上傳的型別是video的型別的  
            JSONObject j=new JSONObject();  
            j.put("title", title);  
            j.put("introduction", introduction);
              
            // 拼裝請求地址  
            String uploadMediaUrl = "http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##";  
            uploadMediaUrl = uploadMediaUrl.replace("##ACCESS_TOKEN##",accessToken);  
  
            URL url = new URL(uploadMediaUrl);  
            String result = null;  
            long filelength = file.length();  
            String fileName=file.getName();  
            String suffix=fileName.substring(fileName.lastIndexOf("."),fileName.length());  
            String type="voice/mp3"; //我這裡寫死  
            /** 
             *  你們需要在這裡根據檔案字尾suffix將type的值設定成對應的mime型別的值 
             */  
            HttpURLConnection con = (HttpURLConnection) url.openConnection();  
            con.setRequestMethod("POST"); // 以Post方式提交表單,預設get方式  
            con.setDoInput(true);  
            con.setDoOutput(true);  
            con.setUseCaches(false); // post方式不能使用快取  
            // 設定請求頭資訊  
            con.setRequestProperty("Connection", "Keep-Alive");  
            con.setRequestProperty("Charset", "UTF-8");
              
            // 設定邊界,這裡的boundary是http協議裡面的分割符,不懂的可惜百度(http 協議 boundary),這裡boundary 可以是任意的值(111,2222)都行  
            String BOUNDARY = "----------" + System.currentTimeMillis();  
            con.setRequestProperty("Content-Type",  
                    "multipart/form-data; boundary=" + BOUNDARY);  
            // 請求正文資訊  
            // 第一部分:  
              
            StringBuilder sb = new StringBuilder();  
              
              
              
            //這塊是post提交type的值也就是檔案對應的mime型別值  
            sb.append("--"); // 必須多兩道線 這裡說明下,這兩個橫槓是http協議要求的,用來分隔提交的引數用的,不懂的可以看看http 協議頭  
            sb.append(BOUNDARY);  
            sb.append("\r\n");  
            sb.append("Content-Disposition: form-data;name=\"type\" \r\n\r\n"); //這裡是引數名,引數名和值之間要用兩次  
            sb.append(type+"\r\n"); //引數的值  
              
            //這塊是上傳video是必須的引數,你們可以在這裡根據檔案型別做if/else 判斷  
            sb.append("--"); // 必須多兩道線  
            sb.append(BOUNDARY);  
            sb.append("\r\n");  
            sb.append("Content-Disposition: form-data;name=\"description\" \r\n\r\n");  
            sb.append(j.toString()+"\r\n");  
              
            /** 
             * 這裡重點說明下,上面兩個引數完全可以解除安裝url地址後面 就想我們平時url地址傳參一樣, 
             * http://api.weixin.qq.com/cgi-bin/material/add_material?access_token=##ACCESS_TOKEN##&type=""&description={} 這樣,如果寫成這樣,上面的 
             * 那兩個引數的程式碼就不用寫了,不過media引數能否這樣提交我沒有試,感興趣的可以試試 
             */  
              
            sb.append("--"); // 必須多兩道線  
            sb.append(BOUNDARY);  
            sb.append("\r\n");  
            //這裡是media引數相關的資訊,這裡是否能分開下我沒有試,感興趣的可以試試  
            sb.append("Content-Disposition: form-data;name=\"media\";filename=\""  
                    + fileName + "\";filelength=\"" + filelength + "\" \r\n");  
            sb.append("Content-Type:application/octet-stream\r\n\r\n");  
            System.out.println(sb.toString());  
            byte[] head = sb.toString().getBytes("utf-8");  
            // 獲得輸出流  
            OutputStream out = new DataOutputStream(con.getOutputStream());  
            // 輸出表頭  
            out.write(head);  
            // 檔案正文部分  
            // 把檔案已流檔案的方式 推入到url中  
            DataInputStream in = new DataInputStream(new FileInputStream(file));  
            int bytes = 0;  
            byte[] bufferOut = new byte[1024];  
            while ((bytes = in.read(bufferOut)) != -1) {  
                out.write(bufferOut, 0, bytes);  
            }  
            in.close();  
            // 結尾部分,這裡結尾表示整體的引數的結尾,結尾要用"--"作為結束,這些都是http協議的規定  
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後資料分隔線  
            out.write(foot);  
            out.flush();  
            out.close();  
            StringBuffer buffer = new StringBuffer();  
            BufferedReader reader = null;  
            // 定義BufferedReader輸入流來讀取URL的響應  
            reader = new BufferedReader(new InputStreamReader(  
                    con.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                buffer.append(line);  
            }  
            if (result == null) {  
                result = buffer.toString();  
            }  
            // 使用JSON-lib解析返回結果  
            JSONObject jsonObject = JSONObject.fromObject(result);  
            if (jsonObject.has("media_id")) {  
                System.out.println("media_id:"+jsonObject.getString("media_id"));  
            } else {  
                System.out.println(jsonObject.toString());  
            }  
            System.out.println("json:"+jsonObject.toString());  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
  
        }  
    } 

}

3.上傳臨時 或者 永久縮圖素材 (註釋掉的地址是臨時素材的)

package weixin.tuwen;

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.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;
import weixin.util.WX_TokenUtil;

public class UploadLinshiSucai {
		//臨時素材地址
//	    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	    //永久素材的地址
	    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
	    public static String uploadFile(File file, String accessToken, String type) throws Exception{
//	        File file = new File(filePath);
	        if(!file.exists() || !file.isFile()) {
	            throw new IOException("檔案不存在!");
	        }

	        String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
	        URL urlObj = new URL(url);

	        //連線
	        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

	        conn.setRequestMethod("POST");
	        conn.setDoInput(true);
	        conn.setDoOutput(true);
	        conn.setUseCaches(false);

	        //請求頭
	        conn.setRequestProperty("Connection", "Keep-Alive");
	        conn.setRequestProperty("Charset", "UTF-8");
	        //conn.setRequestProperty("Content-Type","multipart/form-data;");

	        //設定邊界
	        String BOUNDARY = "----------" + System.currentTimeMillis();
	        conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+BOUNDARY);

	        StringBuilder sb = new StringBuilder();
	        sb.append("--");
	        sb.append(BOUNDARY);
	        sb.append("\r\n");
	        sb.append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n");
	        sb.append("Content-Type:application/octet-stream\r\n\r\n");

	        byte[] head = sb.toString().getBytes("utf-8");

	        //輸出流
	        OutputStream out = new DataOutputStream(conn.getOutputStream());

	        out.write(head);

	        //檔案正文部分
	        DataInputStream in = new DataInputStream(new FileInputStream(file));
	        int bytes = 0;
	        byte[] bufferOut = new byte[1024];
	        while((bytes = in.read(bufferOut))!=-1) {
	            out.write(bufferOut,0,bytes);
	        }
	        in.close();

	        //結尾
	        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
	        out.write(foot);
	        out.flush();
	        out.close();

	        //獲取響應
	        StringBuffer buffer = new StringBuffer();
	        BufferedReader reader = null;
	        String result = null;

	        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        String line = null;
	        while((line = reader.readLine()) != null) {
	            buffer.append(line);
	        }
	        if(result == null) {
	            result = buffer.toString();
	        }
	        reader.close();

	        //需要新增json-lib  jar包
	        JSONObject json = JSONObject.fromObject(result);
	        System.out.println(json);
	        String mediaId = json.getString("thumb_media_id");

	        return mediaId;
	    }
	    
	    
		public static void main(String[] args) throws Exception {
			String access_token = WX_TokenUtil.getWXToken().getAccessToken();
			File file = new File("C:/Users/Music/timg.jpg");
			String type = "thumb";
			uploadFile(file,access_token,type);
		}


}

4.上傳圖文訊息素材

package weixin.tuwen;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import com.alibaba.fastjson.JSONObject;
import com.qs.util.httpspost.HttpsUtil;

import weixin.tuwen.pojo.Tuwen;
import weixin.util.WX_TokenUtil;

/**
 * 上傳圖文訊息素材【訂閱號與服務號認證後均可用】
 *  http請求方式: POST
	https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
 * @author v_yiqqin
 */
public class TuwenUpload {
	
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException{
	
		String access_token = WX_TokenUtil.getWXToken().getAccessToken();
//		System.out.println(access_token);
//		String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token="+access_token;
		//永久素材地址
		String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+access_token;
		Tuwen tt = new Tuwen();
		tt.setThumb_media_id("aprI7dnR4XeWcPEJcjLeIUjcDJv658pne4-2FUzEb6A");
		tt.setAuthor("kevin");
		tt.setTitle("圖文測試66666");
		tt.setContent_source_url("www.baidu.com");
		tt.setContent("測試內容666666");
		tt.setDigest("描述666666");
		tt.setShow_cover_pic(1);
		
		JSONObject json = (JSONObject) JSONObject.toJSON(tt);
		String str = json.toString();
		str = "{"+"\"articles\":["+str+"]"+"}";
		byte[] result = HttpsUtil.post(url, str, "utf-8");
		String strs = new String(result);
		System.out.println(strs);
	}
}

5.最後一步,傳送圖文訊息

package weixin.tuwen;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.qs.util.httpspost.HttpsUtil;

import weixin.tuwen.pojo.GetUserList;
import weixin.tuwen.pojo.Media_id;
import weixin.tuwen.pojo.SendPojo;
import weixin.tuwen.pojo.Text;
import weixin.util.WX_TokenUtil;

public class SendMessage {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 */
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
		String access_token = WX_TokenUtil.getWXToken().getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+access_token;
		//先獲取使用者openid列表
		List userList = GetUserList.getUserList();
		String openid = userList.toString();
		System.out.println(openid);
		Media_id m = new Media_id();
		m.setMedia_id("aprI7dnR4XasdsafdghjewetrsdKiawoXw6RFzGM");
		JSONObject json1 = (JSONObject) JSONObject.toJSON(m);
		String str1 = json1.toString();
		System.out.println(str1);
		//封裝請求引數
		SendPojo sp = new SendPojo();
		sp.setTouser(userList);
		sp.setMpnews(str1);
		sp.setMsgtype("mpnews");
		sp.setSend_ignore_reprint(0);
		

		
//		Text t = new Text();
//		t.setContent("hello from boxer");
//		JSONObject json1 = (JSONObject) JSONObject.toJSON(t);
//		String str1 = json1.toString();
//		System.out.println(str1);
//		
//		SendPojo sp = new SendPojo();
//		sp.setTouser(userList);
//		sp.setMsgtype("text");
//		sp.setText(str1);
//		
		JSONObject json = (JSONObject) JSONObject.toJSON(sp);
		String str = json.toString();
		str= str.replace("\\", "");  
		str= str.replace("\"{", "{");
		str= str.replace("}\"", "}");
		System.out.println(str);
		
		byte[] result = HttpsUtil.post(url, str, "utf-8");
		String strs = new String(result);
		System.out.println(strs);
	}

}

6.獲取使用者列表(群發使用者)

package weixin.tuwen.pojo;

import java.util.List;

import com.alibaba.fastjson.JSONObject;

import weixin.util.WX_HttpsUtil;
import weixin.util.WX_TokenUtil;

public class GetUserList {

	/**
	 * @param args
	 */
	public static List getUserList() {
		String access_token = WX_TokenUtil.getWXToken().getAccessToken();
		String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token;
		JSONObject result = WX_HttpsUtil.httpsRequest(url, "GET",null);
		JSONObject resultJson = new JSONObject(result);
		JSONObject data = (JSONObject) resultJson.get("data");
		List openidlist = (List) data.get("openid");
		return openidlist;
	}

}