微信公众号开发--给指定用户发送编辑好的信息

主逻辑代码
**说明:**这一段代码可以粘贴到任何一个地方,当你的流程走到某一步之后需要给用户发送信息,这一段就是发送的信息。

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();
        }
    }
}

喜欢的可以收藏,关注,评论,不喜欢的就当没看见

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值