[java] view plain copy
package cn.com.taiji.oosweb.httpserver;
import java.util.Map;
public class WechatTemplate {
private String touser; //openId
private String template_id;
private String url;
private Map<String, TemplateData> 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<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
创建工具类NetTools:
package cn.com.taiji.oosweb.web.wx.authdeny;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
public class NetTools {
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("连接异常,超时;"+ce.getMessage());
} catch (Exception e) {
System.out.println("https请求异常:"+e.getMessage());
}
return jsonObject;
}
}
方法测试类main:
package cn.com.taiji.oosweb.httpserver;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.taiji.oosweb.manager.helper.JsonUtil;
import cn.com.taiji.oosweb.web.wx.authdeny.MyX509TrustManager;
import cn.com.taiji.oosweb.web.wx.authdeny.NetTools;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
public class method {
static String appsecret ="";
static String appId ="";
public static void main(String[] args) {
appId = "wx2faec6d97bb8d50a";
appsecret = "ed4a837d65d26018e4eb96cc1006c078";
String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//获取access_token
requestUrl = requestUrl.replace("APPID", appId);
requestUrl = requestUrl.replace("APPSECRET", appsecret);
JSONObject jsonObject = NetTools.httpsRequest(requestUrl, "GET", null);
String access_token = (String) jsonObject.get("access_token");
//获取行业信息
String hyxxUrl = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=ACCESS_TOKEN";
hyxxUrl = hyxxUrl.replace("ACCESS_TOKEN", access_token);
JSONObject hyxx = NetTools.httpsRequest(hyxxUrl, "GET", null);
String primary_industry = (String) JsonUtil.getJSONObject(hyxx.get("primary_industry").toString()).get("first_class");
//获取模板id,此处使用的是POST方式提交,使用工具类NetTools时放参数的格式如下
String mbIdUrl = "https://api.weixin.qq.com/cgi-bin/template/api_add_template";
JSONObject mbId = NetTools.httpsRequest(mbIdUrl, "POST", "access_token="+access_token+"&template_id_short=TM00050");
//获取模板列表
String mblbUrl = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=ACCESS_TOKEN";
hyxxUrl = mblbUrl.replace("ACCESS_TOKEN", access_token);
JSONObject mblb = NetTools.httpsRequest(hyxxUrl, "GET", null);
String accessToken =access_token;
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTemplate_id((String)mbId.get("template_id"));
wechatTemplate.setTouser("wd6wkXKIQf5qGBfYB_MFZ8w");
wechatTemplate.setUrl("http://music.163.com/#/song?id=27867140");
Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#000000");
first.setValue("您的户外旅行活动订单已经支付完成,可在我的个人中心中查看。");
m.put("first", first);
TemplateData keyword1 = new TemplateData();
keyword1.setColor("#000000");
keyword1.setValue("1.2发现尼泊尔—人文与自然的旅行圣地 ");
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#000000");
keyword2.setValue("5000元");
m.put("keyword2", keyword2);
TemplateData keyword3 = new TemplateData();
keyword3.setColor("#000000");
keyword3.setValue("2017.1.2");
m.put("keyword3", keyword3);
TemplateData keyword4 = new TemplateData();
keyword4.setColor("#000000");
keyword4.setValue("5");
m.put("keyword4", keyword4);
TemplateData remark = new TemplateData();
remark.setColor("#000000");
remark.setValue("请届时携带好身份证件准时到达集合地点,若临时退改将产生相应损失,敬请谅解,谢谢!");
m.put("remark", remark);
wechatTemplate.setData(m);
try {
sendTemplateMessage(accessToken, wechatTemplate);
} catch (Exception e) {
// logger.info("异常"+e.getMessage());
}
}
private final static String SEND_TEMPLAYE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
public static void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) {
String jsonString = new Gson().toJson(wechatTemplate).toString();
// System.err.println("-------"+jsonString);
String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject failOrsucess = NetTools.httpsRequest(requestUrl, "POST",jsonString );
System.err.println(failOrsucess);
}
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
{
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try
{
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}
if (outputStr != null) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
// jsonObject = JSON.parseObject(buffer.toString());
// jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
// logger.error("Weixin server connection timed out.");
} catch (Exception e) {
// logger.error("https request error:{}", e);
}
return jsonObject;
}
}