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. MapReduce全局变量之捉虫记

    全局变量 写MapReduce程序时候,有时候须要用到全局变量,经常使用的全局变量实现由三种方式: 通过作业的Configuration传递全局变量.作业初始化的时候.conf.set(),须要的时候 ...

  2. 转://tcpdump抓包实例

    基本语法 ========过滤主机--------- 抓取所有经过 eth1,目的或源地址是 192.168.1.1 的网络数据# tcpdump -i eth1 host 192.168.1.1- ...

  3. A - Dogs and Cages HDU - 6243(组合数学)

    题意:在1—n的数字,放入编号为1—n的框中,每个框只放一个数字,问数字与所放的框的编号不同的个数的期望值. 思路:在1—n中任选一个数字,设为k 那么 k 排到非k编号的框中的方案数为 n!-(n- ...

  4. go标准库的学习-reflect

    参考: https://studygolang.com/pkgdoc http://c.biancheng.net/golang/concurrent/ 导入方式: import "refl ...

  5. mysql 数据表 增删改查

    用户操作: mysql -u root -p 登录root用户: SHOW DATABASES; 显示所有的数据库名称: USE linuxcast; 切入linuxcast数据库: CREATE T ...

  6. SkylineGlobe 邻近度(Proximity)分析JavaScript源代码

    邻近度(Proximity)描述了地理空间中两个地物距离相近的程度,是空间分析的一个重要手段. <html xmlns="http://www.w3.org/1999/xhtml&qu ...

  7. 阿里云telnet 3306端口失败

    在阿里云的服务器上安装了MySQL, 然后远程访问总是不通. 查询了很久,排查思路如下: 检查mysql是否启动 检查本机3306端口是否处于监听状态 检查阿里云控制台是否开启了安全限制 检查mysq ...

  8. VS2017中 C# dll引用(C生成dll,C++生成dll)小结 - 简书

    原文:VS2017中 C# dll引用(C生成dll,C++生成dll)小结 - 简书 dll引用小结 一.dll与应用程序 动态链接库(也称为DLL,即为“Dynamic Link Library” ...

  9. 在SpringMVC中使用HandlerInterceptor来实现拦截器功能

    需求:我们需要在请求某些特定的URL(URL格式为Restful格式)时添加拦截器,以实现进行权限控制. 如:/ResourcePlan/projectCode/P1503127828/PROJECT ...

  10. 使用Python遇到:'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte 问题

    查看你的HTTP头部是否有如下头部信息:"Accept-Encoding": "gzip, deflate" 这条信息代表本地可以接收压缩格式的数据,而服务器在 ...