主逻辑代码
**说明:**这一段代码可以粘贴到任何一个地方,当你的流程走到某一步之后需要给用户发送信息,这一段就是发送的信息。
String message ="这里是编写你要给用户发什么信息";
// message要发送的信息String
// username就是用户的openid,在同一个公众号下,openid唯一
// accesstoken就是从数据获取的,要是不清楚可以进我的博客看“微信公众号开发--获取access_token和Ticket”里面写的很详细
HfMessage.sendTextMessageToUser(message, username, accesstoken);
工具类
import net.sf.json.JSONArray;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* 给指定用户发送信息
*/
public class HfMessage {
/**
* 连接请求微信后台接口
*/
public static void connectWeiXinInterface(String action,String json){
URL url;
try {
url = new URL(action);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os = http.getOutputStream();
os.write(json.getBytes("UTF-8"));// 传入参数
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String result = new String(jsonBytes, "UTF-8");
System.out.println("请求返回结果:"+result);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 微信公共账号发送给账号
*/
public static void sendTextMessageToUser(String content,String toUser,String accessToken){
String json = "{\"touser\": \""+toUser+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+content+"\"}}";
//获取请求路径
String action = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
System.out.println("json:"+json);
try {
connectWeiXinInterface(action,json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
喜欢的可以收藏,关注,评论,不喜欢的就当没看见