使用Java进行微信公众号推送模板消息,使用微信开放平台的API。
首先,您需要获取微信公众号的access_token,使用以下代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class AccessTokenUtil {
public static String getAccessToken(String appId, String appSecret) {
String accessToken = null;
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonObject = new JSONObject(response.toString());
accessToken = jsonObject.getString("access_token");
}
} catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
}
然后,您可以使用以下代码向用户发送模板消息:
import net.sf.json.JSONObject;
public class TemplateMessageUtil {
public static void sendTemplateMessage(String accessToken, String openId, String templateId, String url, JSONObject data) {
String apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
try {
URL obj = new URL(apiUrl);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
JSONObject jsonBody = new JSONObject();
jsonBody.put("touser", openId);
jsonBody.put("template_id", templateId);
jsonBody.put("url", url);
jsonBody.put("data", data);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(jsonBody.toString());
out.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jsonObject = new JSONObject(response.toString());
int errorCode = jsonObject.getInt("errcode");
if (errorCode == 0) {
System.out.println("Template message sent successfully.");
} else {
System.out.println("Failed to send template message. Error code: " + errorCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用时,您需要提供正确的appId
、appSecret
、accessToken
、openId
、templateId
、url
和data
。data
是一个包含模板消息内容的JSONObject对象。
请注意,以上代码只是一个简单的示例,您可能还需要处理异常等情况。