java发送消息到公众号代码
时间: 2024-04-22 22:23:55 浏览: 213
要使用 Java 发送消息到公众号,你需要先获取到对应公众号的 AppID 和 AppSecret,然后使用 Java 的 HTTP 客户端发送 POST 请求到微信公众平台提供的 API 地址。以下是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class WeChatMessageSender {
public static void main(String[] args) {
String appId = "your_app_id";
String appSecret = "your_app_secret";
String openId = "user_open_id";
String message = "Hello, world!";
try {
// 获取 access_token
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
URL url = new URL(accessTokenUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String accessToken = response.toString().split("\"access_token\":")[1].split(",")[0].replaceAll("\"", "");
// 发送消息
String messageUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
url = new URL(messageUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoOutput(true);
String postData = "touser=" + openId + "&msgtype=text&text=" + URLEncoder.encode(message, "UTF-8");
connection.getOutputStream().write(postData.getBytes());
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("消息发送成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先获取了对应公众号的 access_token,然后使用 access_token 和用户的 open_id 发送了一条文本消息。注意:在实际使用中,你需要根据你的具体需求修改 AppID、AppSecret、open_id 和消息内容等信息。
阅读全文