微信图文消息

微信高级群发接口

微信官方接口文档说明:

http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html#.E4.B8.8A.E4.BC.A0.E5.9B.BE.E6.96.87.E6.B6.88.E6.81.AF.E5.86.85.E7.9A.84.E5.9B.BE.E7.89.87.E8.8E.B7.E5.8F.96URL.E3.80.90.E8.AE.A2.E9.98.85.E5.8F.B7.E4.B8.8E.E6.9C.8D.E5.8A.A1.E5.8F.B7.E8.AE.A4.E8.AF.81.E5.90.8E.E5.9D.87.E5.8F.AF.E7.94.A8.E3.80.91

一:上传多媒体文件接口(type==thum 上传缩略图 返回  thumb_media_id

微信官方文档:http://mp.weixin.qq.com/wiki/5/963fc70b80dc75483a271298a76a8d59.html

接口: https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE

二:上传图文消息素材【订阅号与服务号认证后均可用】[返回media_id]

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
{
   "articles": [
		 {
                        "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
                        "author":"xxx",
			 "title":"Happy Day",
			 "content_source_url":"www.qq.com",
			 "content":"content",
			 "digest":"digest",
                        "show_cover_pic":"1"
		 },
		 {
                        "thumb_media_id":"qI6_Ze_6PtV7svjolgs-rN6stStuHIjs9_DidOHaj0Q-mwvBelOXCFZiq2OsIU-p",
                        "author":"xxx",
			 "title":"Happy Day",
			 "content_source_url":"www.qq.com",
			 "content":"content",
			 "digest":"digest",
                        "show_cover_pic":"0"
		 }
   ]
}

三: 获取所有关注者openid

 微信官方接口说明文档:http://mp.weixin.qq.com/wiki/0/d0e07720fc711c02a3eab6ec33054804.html

 接口:

https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID

四:根据OpenID列表群发【订阅号不可用,服务号认证后可用】

    接口:   

http请求方式: POST
https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=ACCESS_TOKEN

  五:代码

 1:上传图片到微信的服务器上的工具类  

 public static String formUpload(String urlStr, String access_token,Map<String, String> textMap,  Map<String, String> fileMap) {  
			   
			    urlStr= urlStr.replace("ACCESS_TOKEN",access_token);
		        String res = "";  
		        HttpURLConnection conn = null;  
		        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符  
		        try {  
		            URL url = new URL(urlStr);  
		            conn = (HttpURLConnection) url.openConnection();  
		            conn.setConnectTimeout(5000);  
		            conn.setReadTimeout(30000);  
		            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; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
		            conn.setRequestProperty("Content-Type",  "multipart/form-data; boundary=" + BOUNDARY);  
		            OutputStream out = new DataOutputStream(conn.getOutputStream());  
		            
		            // text  
		            if (textMap != null) {  
		                StringBuffer strBuf = new StringBuffer();  
		                Iterator iter = textMap.entrySet().iterator();  
		                while (iter.hasNext()) {  
		                    Map.Entry entry = (Map.Entry) iter.next();  
		                    String inputName = (String) entry.getKey();  
		                    String inputValue = (String) entry.getValue();  
		                    if (inputValue == null) {  
		                        continue;  
		                    }  
		                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
		                    strBuf.append("Content-Disposition: form-data; name=\""  
		                            + inputName + "\"\r\n\r\n");
		                    strBuf.append(inputValue);  
		                }  
		                out.write(strBuf.toString().getBytes());  
		            }  
		  
		            // file  
		            if (fileMap != null) {  
		                Iterator iter = fileMap.entrySet().iterator();  
		                while (iter.hasNext()) {  
		                    Map.Entry entry = (Map.Entry) iter.next();  
		                    String inputName = (String) entry.getKey();  
		                    String inputValue = (String) entry.getValue();  
		                    if (inputValue == null) {  
		                        continue;  
		                    }  
		                    File file = new File(inputValue);  
		                    String filename = file.getName();  
		                    
		                    String contentType = new MimetypesFileTypeMap()  
		                            .getContentType(file);  
		                    if (filename.endsWith(".png")) {  
		                        contentType = "image/png";  
		                    }  
		                    if (filename.endsWith(".jpg")) {  
		                        contentType = "image/png";  
		                    }  
		                    if (contentType == null || contentType.equals("")) {  
		                        contentType = "application/octet-stream";  
		                    }  
		                    
		                    StringBuffer strBuf = new StringBuffer();  
		                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
		                            "\r\n");  
		                    strBuf.append("Content-Disposition: form-data; name=\""  
		                            + inputName + "\"; filename=\"" + filename   
		                            + "\"\r\n");  
		                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
		                    out.write(strBuf.toString().getBytes());  
		                    
		                    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[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
		            out.write(endData);  
		            out.flush();  
		            out.close();  
		  
		            // 读取返回数据  
		            StringBuffer strBuf = new StringBuffer();  
		            BufferedReader reader = new BufferedReader(new InputStreamReader(  
		                    conn.getInputStream()));  
		            String line = null;  
		            while ((line = reader.readLine()) != null) {  
		                strBuf.append(line).append("\n");  
		            }  
		            res = strBuf.toString();  
		            reader.close();  
		            reader = null;  
		        } catch (Exception e) {  
		            System.out.println("发送POST请求出错。" + urlStr);  
		            e.printStackTrace();  
		        } finally {  
		            if (conn != null) {  
		                conn.disconnect();  
		                conn = null;  
		            }  
		        }  
		        return res;  
		    }
 
 

2:访问微信服务器的接口的工具类

public static JSONObject httpRequest(String requestUrl,
				String requestMethod, String outputStr) {
			JSONObject jsonObject = null;
			StringBuffer buffer = new StringBuffer();
			try {
				// /1、解决https请求的问题

				// 创建SSLContext对象,并使用我们指定的信任管理器初始化
				TrustManager[] tm = { new X509CertificateManager() };
				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);

				// /2、兼容GET、POST两种方式

				// 设置请求方式(GET/POST)
				httpUrlConn.setRequestMethod(requestMethod);

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

				// /3、兼容有数据提交、无数据提交两种情况

				// 当有数据需要提交时
				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) {
			} catch (Exception e) {
			}
			return jsonObject;
		}

3:访问微信服务器的https方法

public static String sendHttpsRequest(String url, String accesstoken, String allParams){
		   
		url=url.replace("ACCESS_TOKEN",accesstoken) ;
		SSLContext sc = null;
		TrustManager[] trustAllCerts = new TrustManager[] {
			new javax.net.ssl.X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) <span style="white-space:pre">			<span style="white-space:pre">	</span>{
			
			}

			public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) <span style="white-space:pre">			<span style="white-space:pre">	</span>{
			
			}
		  }
	     };

	   try {
			sc = SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
		}

		HostnameVerifier hv = new HostnameVerifier() {
			public boolean verify(String urlHostName, SSLSession session) {
				return urlHostName.equals(session.getPeerHost());
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(hv);

		try {
			URL t_url = new URL(url);
			HttpsURLConnection ucon = (HttpsURLConnection) t_url.openConnection();
			ucon.setConnectTimeout(30000);
			ucon.setReadTimeout(30000);
			ucon.setDoOutput(true);
			ucon.setDoInput(true);
			ucon.setUseCaches(false);
			ucon.setRequestMethod("GET");
			ucon.setRequestProperty("Accept-Charset", "utf-8");
			ucon.setRequestProperty("contentType", "text/html");
			ucon.setRequestProperty("pageEncoding", "utf-8");
			ucon.connect();
			if(allParams!=null)
			{
				BufferedOutputStream bos = new BufferedOutputStream(ucon.getOutputStream());
				bos.write(allParams.getBytes("UTF-8"));
				bos.flush();
				bos.close();
			}
			// 接收响应
			int statuscode = ucon.getResponseCode();
			String statusmsg = ucon.getResponseMessage();
			System.out.println(statuscode + statusmsg);
			// 判断服务器是否正确响应
			String reJson = null;
			if (statuscode == 200) {
				InputStream is = ucon.getInputStream();
				InputStreamReader r = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(r);
				// 读取响应并转为JSON
				reJson = br.readLine();
				//System.out.println(new String(reJson.getBytes("GBK"), "utf-8"));
				
				// 关闭流
				br.close();
				r.close();
				is.close();
			}
			return reJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

4:拼接图文消息格式 JSON

public static String GetArticlesJsonStr(List<Message> list,String accesstoken ){
    		JSONArray array=new JSONArray();
    		for(int i=0;i<list.size();i++){
    			     Message message=list.get(i);
    			     //上传媒体 返回媒体ID
    			     Map<String, String> fileMap = new HashMap<String, String>();  
    			     fileMap.put("userfile",img_url+message.getMessage_imgurl());
    			     String ret_media_id1 =HttpsTool.formUpload(media_img_url,accesstoken, null, fileMap);
    			     System.out.println("媒体:"+ret_media_id1);
    			     JSONObject  json_img = JSONObject.fromObject(ret_media_id1);
    			     String media_id_no1=json_img.getString("thumb_media_id");   
    			     //上传图文素材 返回media_id
    			     JSONObject jsonobject=new JSONObject();
    			     jsonobject.put("thumb_media_id", media_id_no1);//媒体ID
    			     jsonobject.put("author", message.getMessage_author());//作者
    			     jsonobject.put("title", message.getMessage_title());//标题
    			     jsonobject.put("content_source_url", message.getMessage_texturl());//原文URL
    			     jsonobject.put("content", message.getMessage_content());//内容
    			     jsonobject.put("digest", message.getMessage_abstract());//摘要
    			     array.put(jsonobject);
    		}
    		JSONObject object=new JSONObject();
    		object.put("articles", array.toString());
    		String message_str=HttpsTool.sendHttpsRequest(messageinfo_url,accesstoken,object.toString());
    		System.out.println("素材:"+message_str);
    		JSONObject  json_message = JSONObject.fromObject(message_str);
    	        String media_id_no2=json_message.getString("media_id");
    		return media_id_no2;
    	}

5:获取关注者openid列表

//获取关注的openid列表
public static List<String> getopenidslist(String access_token){
    		List<String> list = new  ArrayList<String>();
    		List<String> list2=getopenids(access_token,null);
    	        for (int i=0;i<list2.size();i++) {
    	    	    list.add(list2.get(i));
    		}
    		while (list2.size() > 0) 
    		 { 
    		     String last_str=list2.get(list2.size()-1);
    	             list2 = getopenids(access_token,last_str.substring(1, last_str.length()-1)); 
    		     for (int i=0;i<list2.size();i++) {
        	    	    System.out.println("openid"+list2.get(i));
        	    	    list.add(list2.get(i));
        		 }
    		} 
    		return  list;
    	}
    	public static List<String> getopenids(String access_token,String next_openid){
    		List<String> list=new ArrayList<String>();
    		String accesstokenUrl = concerned_openid_url.replace("ACCESS_TOKEN", access_token).replace("NEXT_OPENID", StringUtils.isBlank(next_openid)?"":next_openid);
    		JSONObject  json = HttpsTool.httpRequest(accesstokenUrl, "GET", null);
    		int  count=Integer.parseInt(json.get("count").toString());
    		if(count>0){
    				 JSONObject str=JSONObject.fromObject(json.getString("data"));
    				 String openidlist=str.getString("openid").substring(1, str.getString("openid").length()-1);
    				 String openids[]= openidlist.split(",");
    				 for(int i=0;i<openids.length;i++){
    					    list.add(openids[i]);
    				}
    					    return list;
    				}else{
    					   return list;
    				}
    	}

6:拼接群发Json字符串

public  static String sendJsonobject(String media_id,List<String> openidlist){
    		   StringBuilder sb = new StringBuilder();
    		   sb.append("{\"touser\":");
    		   sb.append(openidlist.toString());
    		   sb.append(",");
    		   sb.append("\"msgtype\":\"mpnews\",");
    		   sb.append("\"mpnews\":{\"media_id\":\"" + media_id + "\"}");
    		   sb.append("}");
    		   return sb.toString();
 }
7:群发
public  static  String send(String media_id,List<String> openidlist,String accesstoken){
    		//群发参数
    		String  messageText=sendJsonobject(media_id,openidlist);
    		String  messageret=HttpsTool.sendHttpsRequest(mass_url,accesstoken,messageText);
    		return messageret;
}









  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值