1. 获取OpenId
(WechatToken 类 是自己根据实际情况而定封装的类)
public static String sendPostForCode(String code) {
WechatToken wechatToken = new WechatToken();
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("appid", wechatToken.getAppId()); //开发者设置中的appId
paramMap.put("secret", wechatToken.getAppSecret()); //开发者设置中的appSecret
paramMap.put("js_code", code); //小程序调用wx.login返回的code
paramMap.put("grant_type", wechatToken.getGrantType()); //默认参数 authorization_code
PrintWriter out = null;
BufferedReader in = null;
String result = "";
String param = "";
Iterator<String> it = paramMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
param += key + "=" + paramMap.get(key) + "&";
}
try {
URL realUrl = new URL(wechatToken.getRequestUrl());
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
// log.error(e.getMessage(), e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return JSON.parseObject(result).getString("openid");
}
2. 发送模板消息
public class WechatMouldUtil {
//token请求的方法
private static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
// in = new BufferedReader(new
// InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
//获取token
private static String getTokon() {
WechatToken wechatToken = new WechatToken();
// 小程序唯一标识
String wxspAppid = wechatToken.getAppId();
// 小程序的 app secret
String wxspSecret = wechatToken.getAppSecret();
//这里直接写死就可以,不用改,用法可以去看api
String grant_type = "client_credential";
//封装请求数据
String params = "grant_type=" + grant_type + "&secret=" + wxspSecret + "&appid=" + wxspAppid;
//发送GET请求
String sendGet = sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
// 解析相应内容(转换成json对象)
JSONObject json = new JSONObject(sendGet);
//拿到accesstoken
return json.get("access_token").toString();
}
//发送模板信息
public String sendWechatmsgToUser(JSONObject data, String openid, String formId) {
final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
String url = TEMPLATE_URL.replace("ACCESS_TOKEN", getTokon());
JSONObject json = new JSONObject();
WxTemplateid wxTemplateid = new WxTemplateid();
try {
json.put("template_id", wxTemplateid.getTemplateid());
json.put("touser", openid);
json.put("form_id", formId);
json.put("data", data);
String result = httpsRequest(url, "POST", json.toString());
JSONObject resultJson = new JSONObject(result);
String errmsg = (String) resultJson.get("errmsg");
if (!"ok".equals(errmsg)) {//如果为errmsg为ok,则代表发送成功。
return "error";
}
} catch (Exception e) {
System.out.println("json数据出错");
return "error";
}
return "success";
}
// 模板信息的请求方式
private static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
try {
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 当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();
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("连接超时");
} catch (Exception e) {
System.out.println("https请求异常");
}
return null;
}
}