JAvaマイクロメッセージテンプレートメッセージプッシュを実現



テンプレートメッセージプッシュインタフェース:
微信公衆プラットフォームAPIリンク:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
テンプレート呼び出しツールクラスについて書きましたが、
JAvaは状況に応じて1つの方法に変更されます
HTTPを付加したPOST呼び出しツール類
異なるテンプレートに基づいて異なるデータを接合する
例:
java实现微信模板消息推送_第1张图片
 
一、テストクラス
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.google.gson.Gson;
import com.phjr.service.huifu.util.HttpClientUtil;


import weixn.Demo;


public class TuiSongTest {


	private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);


	//      
	private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	private final String APPID = "";
	private final String SECRET = "";
	//    ACCESS_TOKEN  
	private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
	+ "&secret=" + SECRET;
	//openId
	private static  String fromUserName="";
	//  ID
	private static String template_id="";
	//        URL
	private static String url="";
	
	
	public static void main(String[] args) {
		TuiSongTest tuiSongTest = new TuiSongTest();
		
		Demo demo = tuiSongTest.getAccess_token();
		String access_token=demo.getAccess_token();
		
		logger.info("          accessToken "+access_token);  
		
		WechatTemplate wechatTemplate = new WechatTemplate();  
		wechatTemplate.setTemplate_id(template_id);  
		wechatTemplate.setTouser(fromUserName);  //      OpenId
		wechatTemplate.setUrl(url); 
		
	private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);


	//      
	private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	private final String APPID = "";
	private final String SECRET = "";
	//    ACCESS_TOKEN  
	private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
	+ "&secret=" + SECRET;
	//openId
	private static  String fromUserName="";
	//  ID
	private static String template_id="";
	//        URL
	private static String url="";
	
	
	public static void main(String[] args) {
		TuiSongTest tuiSongTest = new TuiSongTest();
		
		Demo demo = tuiSongTest.getAccess_token();
		String access_token=demo.getAccess_token();
		
		logger.info("          accessToken "+access_token);  
		
		WechatTemplate wechatTemplate = new WechatTemplate();  
		wechatTemplate.setTemplate_id(template_id);  
		wechatTemplate.setTouser(fromUserName);  //      OpenId
		wechatTemplate.setUrl(url); 
             //             
 Map m = new HashMap();  
        TemplateData first = new TemplateData();   
        first.setColor("#000000"); 
        first.setValue("           ");  
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue("136****1234");
        m.put("keyword1", keyword1);  
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue("2018-06-10 10:23:00");
        m.put("keyword2", keyword2);
        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("  136****1234         ");
        m.put("remark", remark);
        wechatTemplate.setData(m);
        try {   
            tuiSongTest.sendTemplateMessage(access_token, wechatTemplate);  
            } catch (Exception e) {       
                logger.info("  "+e.getMessage());  
        }  
        }

    public void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) {           String jsonString = new Gson().toJson(wechatTemplate).toString();          String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);        logger.info("    ",jsonString);     //   post     json       String json = HttpClientUtil.sendHttpPostJson(requestUrl, jsonString);           WeiXinResponse weiXinResponse = new Gson().fromJson(json, WeiXinResponse.class);     logger.info("jsonObject="+weiXinResponse);     if (null != weiXinResponse) {           int errorCode = weiXinResponse.getErrcode();            if (0 == errorCode) {               logger.info("        ");           } else {               String errorMsg = weiXinResponse.getErrmsg();             logger.info("        ,    "+errorCode+",     "+ errorMsg);           }       }   }   public Demo getAccess_token() { try { String access_token = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(aturl); HttpResponse response = client.execute(request); String httpGet = HttpClientUtil.sendHttpGet(aturl); Gson gson=new Gson(); Demo jsonResult=new Demo(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(response.getEntity());      System.out.println("get    :" + strResult);         System.out.println("    " +response.getStatusLine().getStatusCode() );          jsonResult = gson.fromJson(strResult, Demo.class); access_token = jsonResult.getAccess_token(); String expires_in =jsonResult.getExpires_in(); logger.info("access_token{}:  expires_in{}:",access_token,expires_in); } return jsonResult; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
        
        
    }

次は関連エンティティです.
public class Demo {

	private String access_token;
	
	private String expires_in;

	public String getAccess_token() {
		return access_token;
	}

	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	public String getExpires_in() {
		return expires_in;
	}

	public void setExpires_in(String expires_in) {
		this.expires_in = expires_in;
	}
	
	
}
import java.util.Map;

public class WechatTemplate {

	
	private String touser;
	
	private String template_id;
	
	private String url;
	
	private Map data;

	public String getTouser() {
		return touser;
	}

	public void setTouser(String touser) {
		this.touser = touser;
	}

	public String getTemplate_id() {
		return template_id;
	}

	public void setTemplate_id(String template_id) {
		this.template_id = template_id;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getData() {
		return data;
	}

	public void setData(Map data) {
		this.data = data;
	}
	
	
	
}

 
public class TemplateData {
    private String value;  
    private String color;  
  
    public String getValue() {  
        return value;  
    }  
  
    public void setValue(String value) {  
        this.value = value;  
    }  
  
    public String getColor() {  
        return color;  
    }  
  
    public void setColor(String color) {  
        this.color = color;  
    }  
}

 
public class WeiXinResponse {

	private Integer  errcode;
	
	private String errmsg;
	
	private String msgid;

	public Integer getErrcode() {
		return errcode;
	}

	public void setErrcode(Integer errcode) {
		this.errcode = errcode;
	}

	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}

	public String getMsgid() {
		return msgid;
	}

	public void setMsgid(String msgid) {
		this.msgid = msgid;
	}
	
	
	
}

 
HttpClientツールクラスの追加
 /**
     *    post     json  
     * 
     * @param httpUrl
     *              
     * @param paramsJson
     *              (   json)
     * 
     */
    public static String sendHttpPostJson(String httpUrl, String paramsJson) {
        HttpPost httpPost = new HttpPost(httpUrl);//   httpPost
        try {
            //     
            if (paramsJson != null && paramsJson.trim().length() > 0) {
                StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
                stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
                httpPost.setEntity(stringEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }
    
 /**
     *   Post  
     * 
     * @param httpPost
     * @return
     */
    private static String sendHttpPost(HttpPost httpPost) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        //     
        String responseContent = null;
        try {
            //      httpClient  .
            httpClient = getHttpClient();
            //       
            httpPost.setConfig(requestConfig);
            //     
            response = httpClient.execute(httpPost);
            //       
            HttpEntity entity = response.getEntity();

 
            //       
            if (response.getStatusLine().getStatusCode() >= 300) {
                throw new Exception(
                        "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
                EntityUtils.consume(entity);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //     
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }