public JsonResult sendMessage(String content) { //获得令牌 // String accessToken = "21_UrWTu7IQt5N5KFlnPRdI4ec4C3vPxyvchJQf5E-yBmFED-uEeT6CF5eLpj9yFY6wloZAP6bYmCBR784_wACmU_MZX70JzumXu7XjT58ykCSNkDUW1qFh3JgJ7qJAtLBuwXDhEAbLYZIEF9cmCUVcAGAOGH"; WxAccesstoken wxAccesstoken = wxAccesstokenMapper.selectByPrimaryKey("E1C969101C0000008E00000000366000"); String accessToken = wxAccesstoken.getAccessToken(); String url = TemplateMessage_Url.replace("ACCESS_TOKEN",accessToken); //调用接口进行发送 try { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type","application/json;charset=utf-8"); HttpResponse res = HttpUtils.doPost2(url,"",null,headers,null, content); String returnJson = EntityUtils.toString(res.getEntity()); return JsonResult.success(returnJson); } catch (Exception e) { e.printStackTrace(); } return null; }
工具类
package com.zt.oa.util; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpUtils { /** * get * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpGet request = new HttpGet(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } /** * post form * * @param host * @param path * @param method * @param headers * @param querys * @param bodys * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, Map<String, String> bodys) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (bodys != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); request.setEntity(formEntity); } return httpClient.execute(request); } /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body.toString().indexOf(" ")<0 /*StringUtils.isNotBlank(body)*/) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost2(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } request.setEntity(new StringEntity(body, "utf-8")); return httpClient.execute(request); } /** * Post stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body.toString().indexOf(" ")<0/*StringUtils.isNotBlank(body)*/) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Delete * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, Object> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } private static String buildUrl(String host, String path, Map<String, Object> querys) throws UnsupportedEncodingException { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(host); if (path.toString().indexOf(" ")<0/*!StringUtils.isBlank(path)*/) { sbUrl.append(path); } if (null != querys) { StringBuilder sbQuery = new StringBuilder(); for (Map.Entry<String, Object> query : querys.entrySet()) { if (0 < sbQuery.length()) { sbQuery.append("&"); } if (query.getKey().indexOf(" ")>0/*StringUtils.isBlank(query.getKey())*/ &&String.valueOf(query.getValue()).indexOf(" ")<0 /*!StringUtils.isBlank(query.getValue())*/) { sbQuery.append(query.getValue()); } if (query.getKey().indexOf(" ")>0/*!StringUtils.isBlank(query.getKey())*/) { sbQuery.append(query.getKey()); if (String.valueOf(query.getValue()).indexOf(" ")<0/*!StringUtils.isBlank(query.getValue())*/) { sbQuery.append("="); sbQuery.append(URLEncoder.encode(String.valueOf(query.getValue()), "utf-8")); } } } if (0 < sbQuery.length()) { sbUrl.append("?").append(sbQuery); } } return sbUrl.toString(); } private static HttpClient wrapClient(String host) { HttpClient httpClient = new DefaultHttpClient(); if (host.startsWith("https://")) { sslClient(httpClient); } return httpClient; } private static void sslClient(HttpClient httpClient) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } }
测试controller
/** * 测试 * @return */ @GetMapping("/sendTest") public JsonResult testSendMessage(){ //创建消息发送实体对象 TemplateMessage templateMessage=new TemplateMessage(); // templateMessage.setUrl("www.baidu.com"); templateMessage.setTouser("oZ5gZ000ftRiKIbZplGit8x0f_M0"); templateMessage.setTemplate_id(templateId); //设置模板标题 Content first=new Content(); first.setValue("您好!您发起了流程审批"); first.setColor("#000"); //设置模板内容 Content keyword1=new Content(); keyword1.setValue("尹东伟发起的车采购审批"); keyword1.setColor("#000"); //设置模板位置 Content keyword2=new Content(); keyword2.setValue("发起"); keyword2.setColor("#000"); //设置设备 Content keyword3=new Content(); keyword3.setValue("尹东伟"); keyword3.setColor("#000"); //设置时间 Content keyword4=new Content(); SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日"); String format1 = format.format(new Date()); keyword4.setValue(format1); keyword4.setColor("#000"); //设置跳转内容 Content remark=new Content(); remark.setValue("请您及时关注流程动态"); remark.setColor("#000"); //创建模板信息数据对象 Data data=new Data(); data.setFirst(first); data.setKeyword1(keyword1); data.setKeyword2(keyword2); data.setKeyword3(keyword3); data.setKeyword4(keyword4); data.setRemark(remark); templateMessage.setData(data); //将封装的数据转成JSON String jsonString = JSON.toJSONString(templateMessage); logger.info(jsonString); JsonResult jsonResult = wxMessageService.sendMessage(jsonString); return jsonResult; }