package com.company.product.manager.busniess.impl;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;

import com.company.product.https.EasySSLProtocolSocketFactory;

/**
*
* @author Renguoqiang 微信公众平台,向用户推送模板消息服务。
*/
public class WeChatMpTemplateMessageService {
public static JSONObject get(HttpClient client, String url)
throws IOException, ClientProtocolException {
GetMethod httpGet = new GetMethod(url);
int responseGet = client.executeMethod(httpGet);
System.out.println(responseGet);
String responseText = httpGet.getResponseBodyAsString();
System.out.println(responseText);
httpGet.releaseConnection();
JSONObject result = JSONObject.fromObject(responseText);
return result;
}

public static HttpClient getClient(String url) {
HttpClient httpClient = new HttpClient();
return httpClient;
}

public static JSONObject getJSONParameters(String templateid,String openid) {
JSONObject first = new JSONObject();
first.put("value", "你好");
//first.put("color", "#C71585");

JSONObject keyword1 = new JSONObject();
keyword1.put("value", "715424629750407168");
keyword1.put("color", "#FF00FF");

JSONObject keyword2 = new JSONObject();
keyword2.put("value", "");
//keyword2.put("color", "#FF00FF");

JSONObject keyword3 = new JSONObject();
keyword3.put("value", "客服人员已经为您确定好类型和费用");
//keyword3.put("color", "#00FFFF");

JSONObject remark = new JSONObject();
remark.put("value", "请登录,确认并支付。");
//remark.put("color", "#0000FF");

JSONObject data = new JSONObject();
data.put("first", first);
data.put("keyword1", keyword1);
data.put("keyword2", keyword2);
data.put("keyword3", keyword3);
data.put("remark", remark);

JSONObject jsonParam = new JSONObject();
jsonParam.put("touser", openid);
jsonParam.put("template_id", templateid);
jsonParam.put("url", "https://www.company.com/");
jsonParam.put("data", data);
return jsonParam;
}

public static List<String> getTemplateList(HttpClient client, String access_token) {
String url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="
+ access_token;
JSONObject result = new JSONObject();
try {
result = get(client, url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

JSONArray jsonArray = result.getJSONArray("template_list");
System.out.println(jsonArray);

ArrayList<String> templateIdList = new ArrayList<String>();
for (Object jsonObject : jsonArray) {
templateIdList.add(((JSONObject) jsonObject)
.getString("template_id"));
}

return templateIdList;
}

public static String getTicket(HttpClient client,String appid,String appsecret)
throws IOException, ClientProtocolException {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appid + "&secret=" + appsecret;

JSONObject result = get(client, url);

String access_token = "";
String key = "access_token";

// JSON反序列化
access_token = result.getString(key);

System.out.println("access_token:" + access_token);

return access_token;
}

public static void main(String[] args) {
// JRE设置代理服务器
// System.setProperty("http.proxyHost", "localhost");
// System.setProperty("http.proxyPort", "8888");
// System.setProperty("https.proxyHost", "localhost");
// System.setProperty("https.proxyPort", "8888");

HttpClient client = null;
String url = "https://api.weixin.qq.com";

client = getClient(url);

// 获得令牌
String access_token = "";
try {
String appid = "wxeadda6b8c0e02111";
String appsecret = "55d6d8b2070989df2ef7518687ec8d11";

access_token = getTicket(client,appid,appsecret);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 获得模板列表
List<String> templateIdList = getTemplateList(client, access_token);

// 发送模板消息
// for(String templateid : templateIdList){
String templateid = "QxTCrTWt4HxS3NTOt_iwzJ4gOdrHIDg1l5pfRcniBBs";
String openid="o8cOBwvAJTSPbOhOInWlb7GYdKu1";
postTemplateMsg(client, access_token, templateid,openid);
// }
}

public static void postTemplateMsg(HttpClient httpClient,
String access_token, String templateid,String openid) {
String securityServerSSLPort = "443";
String securityServerHost = "api.weixin.qq.com";
String securityServerActionUri = "cgi-bin/message/template/send?access_token="
+ access_token;
String securityServerHttpsPort = "80";

String body = getJSONParameters(templateid,openid).toString();

httpClient = getClient(securityServerHost);

Protocol easyhttps = new Protocol("https",
new EasySSLProtocolSocketFactory(),
Integer.valueOf(securityServerSSLPort));
HostConfiguration hc = new HostConfiguration();
PostMethod httpMethod = new org.apache.commons.httpclient.methods.PostMethod(
"https://" + securityServerHost + "/" + securityServerActionUri);
try {
Protocol.registerProtocol("https", easyhttps);

httpClient.getParams().setContentCharset(
StandardCharsets.UTF_8.name());

hc.setHost(securityServerHost,
Integer.valueOf(securityServerHttpsPort), easyhttps);

if (StringUtils.isNotBlank(body)) {
StringRequestEntity entity = new StringRequestEntity(body,
"application/json;charset="
+ StandardCharsets.UTF_8.name().toLowerCase(),
StandardCharsets.UTF_8.name());

httpMethod.setRequestEntity(entity);
}

int result = httpClient.executeMethod(hc, httpMethod);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
String strRespBody = httpMethod.getResponseBodyAsString();
System.out.println(strRespBody);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpMethod.releaseConnection();
}
}
}

Java使用HTTPClient3.0.1开发的公众平台消息模板的推送功能的更多相关文章

  1. Java使用HTTPClient4.3开发的公众平台消息模板的推送功能

    代码引用,参考文章:http://www.cnblogs.com/feiyun126/p/4778556.html,表示感谢! package com.yuanchuangyun.cyb.manage ...

  2. 如何用Nearby Service开发针对附近人群的精准广告推送功能

      当你想找一家餐厅吃饭,却不知道去哪家,这时候手机跳出一条通知,为你自动推送附近优质餐厅的信息,你会点击查看吗?当你还在店内纠结于是否买下一双球鞋时,手机应用给了你发放了老顾客5折优惠券,这样的广告 ...

  3. 微信开发——微信公众平台实现消息接收以及消息的处理(Java版)

    本文主要讲述了如何在微信公众平台实现消息接收以及消息的处理,使用java语言开发,现在把实现思路和代码整理出来分先给兄弟们,希望给他们带来帮助. 温馨提示: 这篇文章是依赖前几篇的文章的. 第一篇:微 ...

  4. 使用Java开发微信公众平台(二)——消息的接收与响应

    上一篇文章(http://www.jerehedu.com/fenxiang/171807_for_detail.htm )中,我们学习了使用Java语言开发微信公众平台的第一部分——环境搭建与开发接 ...

  5. 使用Java开发微信公众平台(四)——消息的接收与响应

    上一篇文章(http://www.jerehedu.com/fenxiang/171807_for_detail.htm )中,我们学习了使用Java语言开发微信公众平台的第一部分——环境搭建与开发接 ...

  6. [c#]asp.net开发微信公众平台(1)数据库设计

    开发微信公众平台之前,先去微信官方了解下大概的情况 这里:http://mp.weixin.qq.com/wiki/index.php :看了之后心里大致有数了,开始设计数据库,尽可能的考虑,未考虑到 ...

  7. [c#]asp.net开发微信公众平台(8)微信9大高级接口,自定义菜单

    前7篇把最基础的消息接收和回复全做完了,  也把高级接口的入口和分拆处理写好了空方法,  此篇接着介绍微信的9大高级接口, 并着重讲解其中的自定义菜单. 微信9大接口为: 1.语音识别接口 2.客服接 ...

  8. 微信公众平台消息接口开发-封装weixin.class.php

    原文:微信公众平台消息接口开发-封装weixin.class.php 一.封装weixin.class.php 由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处 ...

  9. C#开发微信公众平台-就这么简单(附Demo)转载

    C#开发微信公众平台-就这么简单(附Demo)  来源:https://www.cnblogs.com/xishuai/p/3625859.html#!comments 写在前面 阅读目录: 服务号和 ...

随机推荐

  1. 使用HostAliases 添加pod 的/etc/hosts

    默认的pod 的/etc/hosts 无法自动数据 [root@master1 ~]# kubectl exec smsservice-5c7ff5f74-bc969 -n testihospital ...

  2. JS进阶之---基本数据类型,引用类型,内存空间

    一.内存空间: 为了便于理解,我们暂且先将Js的内存分为栈内存和堆内存. JavaScript具有垃圾自动回收机制,内存的分配与回收都完全实现了自动管理.所以我们在开发时一般会忽视内存空间的问题.但是 ...

  3. 转载 +function ($) { "use strict";}(window.jQuery);全面分析

    转载 https://www.cnblogs.com/cndotabestdota/p/5664112.html +function ($) { "use strict";}(wi ...

  4. 深入理解mybatis原理, Mybatis初始化SqlSessionFactory机制详解(转)

    文章转自http://blog.csdn.net/l454822901/article/details/51829785 对于任何框架而言,在使用前都要进行一系列的初始化,MyBatis也不例外.本章 ...

  5. 广告牌LED灯阵

    大家都知道广告牌里面原来都是灯管,现在开始更换成LED灯了,下面是我在现场拍的图片: 下面这个图片是LED灯条,铝基板打印电路,TM1812驱动,该IC可以接受4组24位数据,然后转发数据(https ...

  6. 2-物联网开发标配方案(51单片机程序介绍+WIFI程序介绍)

    上一节  https://www.cnblogs.com/yangfengwu/p/9944438.html 购买云服务器安装MQTT就不用说了,以前写过文章介绍 https://www.cnblog ...

  7. HashMap 的实现原理

    hashMap用了一个名字为table的数组:还有若干个名字为entry的链表.看hashMap是如何应用这些数据结构的.用插 入<key,value>举例:hashMap首先会通过key ...

  8. Unity报错 GameObject is already being activated or deactivated

    unity 在OnDisable 方法里设置父节点会报这个错. void OnDisable() { // transform.parent = oldParent; transform.SetPar ...

  9. Codeforces round 1083

    Div1 526 这个E考试的时候没调出来真的是耻辱.jpg A 求个直径就完事 #include<cstdio> #include<algorithm> #include&l ...

  10. (转)对一个deb包的解压、修改、重新打包全过程方法

    转自:https://blog.csdn.net/yygydjkthh/article/details/36695243 Reference: http://www.debian.org/doc/ma ...