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

 package com.yuanchuangyun.cyb.manager.busniess.impl;

 import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject; /**
* 依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar
* @author Renguoqiang
*
*/
public class WeiXinTemplateMessageService { public static final int connTimeout=10000;
public static final int readTimeout=10000;
public static final String charset="UTF-8";
private static HttpClient client = null; static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
} public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
} public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
} public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm(url, params, null, connTimeout, readTimeout);
} public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
SocketTimeoutException, Exception {
return postForm(url, params, null, connTimeout, readTimeout);
} public static String get(String url) throws Exception {
return get(url, charset, null, null);
} public static String get(String url, String charset) throws Exception {
return get(url, charset, connTimeout, readTimeout);
} /**
* 发送一个 Post 请求, 使用指定的字符集编码.
*
* @param url
* @param body RequestBody
* @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
* @param charset 编码
* @param connTimeout 建立链接超时时间,毫秒.
* @param readTimeout 响应超时时间,毫秒.
* @return ResponseBody, 使用指定的字符集编码.
* @throws ConnectTimeoutException 建立链接超时异常
* @throws SocketTimeoutException 响应超时
* @throws Exception
*/
public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
throws ConnectTimeoutException, SocketTimeoutException, Exception {
HttpClient client = null;
HttpPost post = new HttpPost(url);
String result = "";
try {
if (StringUtils.isNotBlank(body)) {
HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
post.setEntity(entity);
}
// 设置参数
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
post.setConfig(customReqConf.build()); HttpResponse res;
if (url.startsWith("https")) {
// 执行 Https 请求.
client = createSSLInsecureClient(); HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxxxxxxxxxxxxxx&secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
HttpResponse responseGet = client.execute(httpGet);
//System.out.println(responseGet);
String responseText = EntityUtils.toString(responseGet.getEntity(), StandardCharsets.UTF_8);
//System.out.println(responseText);
httpGet.releaseConnection();
String access_token = "";
access_token = responseText.replaceAll("(?s).*access_token\":\"", "").replaceAll("(?s)\",\"expires_in.*", "");
System.out.println("access_token:"+access_token); post.setURI(new URI(post.getURI()+access_token)); res = client.execute(post);
} else {
// 执行 Http 请求.
client = WeiXinTemplateMessageService.client;
res = client.execute(post);
}
result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
post.releaseConnection();
if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
} /**
* 提交form表单
*
* @param url
* @param params
* @param connTimeout
* @param readTimeout
* @return
* @throws ConnectTimeoutException
* @throws SocketTimeoutException
* @throws Exception
*/
public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
SocketTimeoutException, Exception { HttpClient client = null;
HttpPost post = new HttpPost(url);
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();
Set<Entry<String, String>> entrySet = params.entrySet();
for (Entry<String, String> entry : entrySet) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
post.setEntity(entity);
} if (headers != null && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
post.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置参数
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
post.setConfig(customReqConf.build());
HttpResponse res = null;
if (url.startsWith("https")) {
// 执行 Https 请求.
client = createSSLInsecureClient();
res = client.execute(post);
} else {
// 执行 Http 请求.
client = WeiXinTemplateMessageService.client;
res = client.execute(post);
}
return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
} finally {
post.releaseConnection();
if (url.startsWith("https") && client != null
&& client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
} /**
* 发送一个 GET 请求
*
* @param url
* @param charset
* @param connTimeout 建立链接超时时间,毫秒.
* @param readTimeout 响应超时时间,毫秒.
* @return
* @throws ConnectTimeoutException 建立链接超时
* @throws SocketTimeoutException 响应超时
* @throws Exception
*/
public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
throws ConnectTimeoutException,SocketTimeoutException, Exception { HttpClient client = null;
HttpGet get = new HttpGet(url);
String result = "";
try {
// 设置参数
Builder customReqConf = RequestConfig.custom();
if (connTimeout != null) {
customReqConf.setConnectTimeout(connTimeout);
}
if (readTimeout != null) {
customReqConf.setSocketTimeout(readTimeout);
}
get.setConfig(customReqConf.build()); HttpResponse res = null; if (url.startsWith("https")) {
// 执行 Https 请求.
client = createSSLInsecureClient();
res = client.execute(get);
} else {
// 执行 Http 请求.
client = WeiXinTemplateMessageService.client;
res = client.execute(get);
} result = IOUtils.toString(res.getEntity().getContent(), charset);
} finally {
get.releaseConnection();
if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
((CloseableHttpClient) client).close();
}
}
return result;
} /**
* 从 response 里获取 charset
*
* @param ressponse
* @return
*/
@SuppressWarnings("unused")
private static String getCharsetFromResponse(HttpResponse ressponse) {
// Content-Type:text/html; charset=GBK
if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
String contentType = ressponse.getEntity().getContentType().getValue();
if (contentType.contains("charset=")) {
return contentType.substring(contentType.indexOf("charset=") + 8);
}
}
return null;
} /**
* 创建 SSL连接
* @return
* @throws GeneralSecurityException
*/
private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException {
return true;
}
}).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
} @Override
public void verify(String host, SSLSocket ssl)
throws IOException {
} @Override
public void verify(String host, X509Certificate cert)
throws SSLException {
} @Override
public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
}); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (GeneralSecurityException e) {
throw e;
}
} public static void main(String[] args) {
try {
JSONObject jsonParam = new JSONObject();
try {
jsonParam.put("touser","o8cOBwvAJTSPbOhOInWlb7GYdKuA");
jsonParam.put("template_id","yke5zUpgAolH5FzxIj8OuzX_qQ2jAEVpFWpzkU7a59c");
jsonParam.put("url","http://weixin.qq.com/download");
jsonParam.put("data","{}");
} catch (JSONException e) {
System.out.println(e);
e.printStackTrace();
}
String jsonStr = jsonParam.toString(); String str= post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=",jsonStr,"application/json", "UTF-8", 10000, 10000);
System.out.println(str);
} catch (ConnectTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

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

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

    package com.company.product.manager.busniess.impl; import java.io.IOException;import java.nio.charse ...

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

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

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

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

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

    本文主要讲述了如何在微信公众平台实现消息接收以及消息的处理,使用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开发微信公众平台----目录汇总-持续更新

    1.[c#]asp.net微信公众平台开发(1)数据库设计 2.[c#]asp.net微信公众平台开发(2)多层架构框架搭建和入口实现 3.[c#]asp.net微信公众平台开发(3)微信消息封装及反 ...

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

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

  9. [c#]asp.net开发微信公众平台(7)前6篇的整体框架demo源码

    这里给出的demo是具备整体框架的微信公众平台源码, 所谓demo就是拿过去就可以直接演示使用的东西,  当然不会具备非常详细的具体到业务层面.数据层面的东西, 每个人都可以在此基础上自由发挥,  只 ...

随机推荐

  1. centos7下安装docker(12.1bridge网络)

    容器默认使用的时bridge网络 docker安装时会创建一个 命令为docker0的linux bridge.如果不指定--network=,运行的容器会默认挂到docker0上 interface ...

  2. python MD5加密方法

    import hashlibhash = hashlib.md5()hash.update('admin')print hash.hexdigest()

  3. 2257: [Jsoi2009]瓶子和燃料

    题意:给你n个数字,然后让你选出k个,这k个数字进行任意组合,问得到的最小结果是多少? 数学知识: 分析:根据题意得出数学公式: 那么,如何在n个之中选出k个呢?其实不用选,因为直接计算各个因子,然后 ...

  4. 在Debian系中快速有效的安装oracle-java

    jre8下载链接  https://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html oracl ...

  5. go标准库的学习-net/rpc/jsonrpc

    参考:https://studygolang.com/pkgdoc 导入方式: import "net/rpc/jsonrpc" jsonrpc包实现了JSON-RPC的Clien ...

  6. 邻接表&链式前向星

    链式前向星: 适合点多.边少的情况 不适用于大量遍历出边的题目(因为cache miss) 邻接表: 如果用邻接表来实现的话,一般就用vector嘛,我们都知道vector都是自动扩容的,在空间满了以 ...

  7. B Long Path

    有n+1个房间.从1-n个房间.每个房间有两扇门.一扇去i+1的房间另一扇去编号为pi的房间. 起点为1,终点为n+1,对应第i个各点,如果我奇数次到达,那么下一步走到a[i]的位子,如果是偶数次到达 ...

  8. 开发板测试-Wi-Fi

    一,下载STM32程序 1,方式一,串口下载(其他下载方式在最后补充) ①调整拨动开关位置 → 短接BOOT0和3.3V → 复位STM32 ②打开下载软件,下载程序 去掉短接 ③测试 {data:s ...

  9. C# 邮箱的使用

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Configurat ...

  10. 火狐浏览器 system error code 1722 rpc服务器不可用和谷歌浏览器的插件application/x-print-ladop不支持

    今天要实现打印的功能,但是火狐浏览器总是出现提示:火狐浏览器 system error code 1722 rpc服务器不可用 后来发现主要是系统服务中的一个windows服务没有打开导致的. 将wi ...