1、在微信公众号中申请模版
2、添加模版,查看模版id
3、发送
public JSONObject sendTemplateMsg(Map<String,String> map) {
String accessToken = Tools.getAccessToken(getAccessTokenUrl());
String urlToken = WxContstants.templateSend.replace("ACCESS_TOKEN",accessToken);
Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#173177");
first.setValue("您已成功预约!");
m.put("first", first);
TemplateData keyword1 = new TemplateData();
keyword1.setColor("#173177");
keyword1.setValue(map.get("userName"));
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#173177");
keyword2.setValue(map.get("sex"));
m.put("keyword2", keyword2);
TemplateData keyword3 = new TemplateData();
keyword3.setColor("#173177");
keyword3.setValue(map.get("serviceName"));
m.put("keyword3", keyword3);
TemplateData keyword4 = new TemplateData();
keyword4.setColor("#173177");
keyword4.setValue(map.get("secondServiceName"));
m.put("keyword4", keyword4);
TemplateData keyword5 = new TemplateData();
keyword5.setColor("#173177");
keyword5.setValue(map.get("createTime"));
m.put("keyword5", keyword5);
TemplateData remark = new TemplateData();
remark.setColor("#000000");
remark.setValue("您的专属顾问将尽快与您联系,请保持手机畅通。客服咨询电话:"+kefutel);
m.put("remark", remark);
JSONObject send = new JSONObject();
send.put("touser",map.get("openId"));
send.put("template_id","8pMxYThj6n6Z_MqRn2Zi8IDMiU2MxGrmkDT9ZRxH9iY");
send.put("url",map.get("url"));
send.put("data",m);
JSONObject jsonObject = HttpClientUtils.httpRequest(urlToken,"POST", String.valueOf(send));
return jsonObject;
}
HttpClientUtils
package com.navitek.maternalweb.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.apache.http.client.config.RequestConfig.DEFAULT;
/**
* @author 26968
*/
@Slf4j
public class HttpClientUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
/**
* 发起http请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl,
String requestMethod, String outputStr) {
JSONObject jsonObject = null;
log.info("请求参数==" + outputStr);
log.info("请求的路径是==" + requestUrl);
StringBuffer buffer = new StringBuffer();
HttpURLConnection httpUrlConn = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
URL url = new URL(requestUrl);
httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setConnectTimeout(25000);
httpUrlConn.setReadTimeout(25000);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod)) {
httpUrlConn.connect();
}
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes(DEFAULT_CHARSET));
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();
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.info("Weixin server connection timed out.");
} catch (Exception e) {
log.info("https request error:{}" + e.getMessage());
} finally {
try {
httpUrlConn.disconnect();
} catch (Exception e) {
log.info("http close error:{}" + e.getMessage());
}
}
log.info("请求返回的值=====" + jsonObject);
return jsonObject;
}
/**
* POST 请求 传递参数为map
*
* @param url
* @param paramMap
*/
public static JSONObject postByMap(String url, Map<String, Object> paramMap) {
//创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(DEFAULT);
// 创建参数队列
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
UrlEncodedFormEntity entity;
JSONObject returnInfo = new JSONObject();
try {
entity = new UrlEncodedFormEntity(formParams, DEFAULT_CHARSET);
httpPost.setEntity(entity);
HttpResponse httpResponse;
httpResponse = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String outString = null;
if (httpEntity != null) {
outString = EntityUtils.toString(httpEntity, DEFAULT_CHARSET);
returnInfo = JSONObject.parseObject(outString);
log.info("调用请求返回的值==" + returnInfo);
}
//释放资源
closeableHttpClient.close();
} catch (UnsupportedEncodingException e) {
log.info("网络通信失败");
} catch (ClientProtocolException e) {
log.info("网络通信失败");
} catch (IOException e) {
log.info("网络通信失败");
}
return returnInfo;
}
}