java 微信推送消息

package com.common.common.util;

import java.net.URLEncoder;

import com.common.common.controller.WeiXinOperationController;
import com.common.common.util.json.Baojing;
import com.common.common.util.json.BaojingData;
import com.common.common.util.json.Common;
import com.common.common.util.json.NotifyReturn;
import com.google.gson.Gson;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


/**
 * 微信推送信息
 * @author Administrator
 *
 */
@Component
public class SendWeixinMessage {
	
	//微信appid   appsecret
	private static String appid = "****************";
	private static String secret = "*************************";
	
	private static WeiXinOperationController wxoc;

	@Autowired
	public void init(WeiXinOperationController wxoc){
		this.wxoc = wxoc;
	}
	
	
	/**
	 * 微信推送消息需在公众号开启模板消息功能并选择模板
	 * 
	 * 
	 * 模板/业务参数
	 * @param alarmId
	 * @param openid
	 * @param title
	 * @param key1
	 * @param key2
	 * @param key3
	 * @param con
	 */
	public static void processRequest(Integer alarmId,String openid,String title,String key1,String key2,String key3,String con) {
		String weiXinToken = getWeiXinToken();//获取微信token
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+weiXinToken;
		String param = "access_token=" + weiXinToken;
		String openId= openid;
		
		Map<String, Object> maps = new HashMap<String, Object>();
		String weiXinOpenId = "";//微信Openid
		
		if(weiXinOpenId !=null&&!weiXinOpenId.equals("")){
				System.out.println("weiXinOpenId----------------------------------------"+weiXinOpenId);
				
				//自定义对象实体类  BaojingData    Common   Baojing   NotifyReturn
				BaojingData baojingData = new BaojingData();
				Common first = new Common(title, "#173177");
				Common keyword1 = new Common(key1, "#173177");
				Common keyword2 = new Common(key2, "#173177");
				Common keyword3 = new Common(key3, "#173177");
				Common remark = new Common(con, "#173177");
				baojingData.setFirst(first);
				baojingData.setKeyword1(keyword1);
				baojingData.setKeyword2(keyword2);
				baojingData.setKeyword3(keyword3);
				baojingData.setRemark(remark);
				
				Baojing baojing = new Baojing();
				String touser = weiXinOpenId;
				String template_id = "jAgs__TpJG5tiBSayG4HSE6dpV6-bQiajPc-LANewwk";//微信模板id,配置后不可更改,唯一
				
				String openid_ = "";
				try {
					DESUtil des = new DESUtil();
					openid_ = des.encrypt(openId);
					openid_ = URLEncoder.encode(openid_,"UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				String topcolor = "#FF0000";
				baojing.setTouser(touser);
				baojing.setTemplate_id(template_id);
				baojing.setTopcolor(topcolor);
				baojing.setData(baojingData);
				Gson gson = new Gson();
				param = gson.toJson(baojing);
				String returnJson = HttpRequest.sendPost(url, param);
				System.out.println("=====================微信推送返回结果returnJson{}:"+returnJson);
				
				//errcode  errmsg
				NotifyReturn returnData = gson.fromJson(returnJson, NotifyReturn.class);
				
				System.out.println("=====================微信推送返回结果转换returnData{}:"+returnData);
				if(returnData.getErrcode().equals("0")){
					System.out.println("推送成功!");
				}else{
					System.out.println("推送失败!");
					System.out.println(returnData.getErrmsg());
				}
		}
	}
	
	
	
	/**
	 * 获取微信token
	 * @return
	 */
	public static String getWeiXinToken() {
		String grant_type = "client_credential";
		String url = "https://api.weixin.qq.com/cgi-bin/token";
		String param = "appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type;
		String tokenResult = HttpRequest.sendGet(url, param);
		Map map = (Map) JSON.parse(tokenResult);
		return map.get("access_token").toString();
	}
	
	
	/**
	 * 获取推送公众号推送模板id
	 * @param weiXinToken    微信access_token
	 * @return
	 */
	public String getTemplate(String weiXinToken){
		String templateId = "";
		try{
			String url1 = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+weiXinToken;
			URL getUrl1=new URL(url1);
			HttpURLConnection http1=(HttpURLConnection)getUrl1.openConnection();
			http1.setRequestMethod("GET"); 
			http1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http1.setDoOutput(true);
			http1.setDoInput(true);
			http1.connect();
			InputStream is1 = http1.getInputStream(); 
			int size1 = is1.available(); 
			byte[] b1 = new byte[size1];
			is1.read(b1);
			String message1 = new String(b1, "UTF-8");
			Map map = (Map) JSON.parse(message1); 
			JSONArray js =JSONObject.parseArray(map.get("template_list").toString());
			Map map1 = (Map)JSON.parse(js.get(0).toString());
			templateId = map1.get("template_id").toString();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return templateId;
	}
	
	
	/**
	 * 1.https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect  需在公众号配置紫链接
	 * 		redirect_uri:微信回调地址   response_type:返回类型code 
	 * 		scope: 1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的   2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。
	 * 2、微信公众号基本配置填写服务器配置
	 * 
	 * 微信回调地址获取微信openid
	 * 根据code
	 * @param request
	 * @return
	 */
	@RequestMapping(value ="/getWxOpenid")
	public String obtainWeiXinOpenid(HttpServletRequest request){
		System.out.println("===================================微信回调开始");
		String openId="";
		try {
			String code = String.valueOf(request.getParameter("code"));
			System.out.println("=============获取code{}:"+code);
			// 网页授权得到用户基本信息接口  
			String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
			
			//获取微信用户openid
			URL getUrl=new URL(url);
			HttpURLConnection http=(HttpURLConnection)getUrl.openConnection();
			http.setRequestMethod("GET"); 
			http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			InputStream is = http.getInputStream(); 
			int size = is.available(); 
			byte[] b = new byte[size];
			is.read(b);
			String message = new String(b, "UTF-8");
			JSONObject json = JSONObject.parseObject(message);
			
			System.out.println("=======================回调参数:"+json);
			openId = json.getString("openid");
			String access_token = json.getString("access_token");
			System.out.println("用户Openid={},access_token={}"+openId+"    "+access_token);
			System.out.println("===================================微信回调结束");
			
			System.out.println();
			
			//获取模板temp_id
			System.out.println("===================================微信获取模板temp_id开始");
			String token = getWeiXinToken();
			System.out.println("==========================access_token{}:"+token);
			
			String url1 = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+token;
			URL getUrl1=new URL(url1);
			HttpURLConnection http1=(HttpURLConnection)getUrl1.openConnection();
			http1.setRequestMethod("GET"); 
			http1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http1.setDoOutput(true);
			http1.setDoInput(true);
			http1.connect();
			InputStream is1 = http1.getInputStream(); 
			int size1 = is1.available(); 
			byte[] b1 = new byte[size1];
			is1.read(b1);
			String message1 = new String(b1, "UTF-8");
			JSONObject json1 = JSONObject.parseObject(message1);
			System.out.println("========模板返回参数json1{}:"+json1);
			
			
			System.out.println("===================================微信获取模板temp_id结束");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return openId;
	}

}



package com.common.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
         // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
    	OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }   
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostByHeader(String url, String param, HashMap<String, String> map) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			for (Object obj : map.keySet()) {
				Object value = map.get(obj);
				conn.setRequestProperty(obj.toString(), value.toString());
				System.out.println(obj.toString()+":"+value.toString());
			}
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值