Java代码 微信公众号推送(代码详细)

用的是idea, 需要修改的地方在于这些地方改了

 

 

然后吧账号密码填写进去就好了  运行类是   Yi   这个类

非常简单 祝大家成功 ,不会的关注私聊  

微信公众号测试注册地址:微信公众平台 (qq.com)

 我用的模板是这个只有一个数据 ,当然这个可以自己添加

 做出来的效果当然上面那个要添加什么只需要在这个类里面添加对应的数据值:

 

 

 

 需要导入的jar包

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.15.RELEASE</version>
        </dependency>

    </dependencies>

public class ABC {
    private int abc=1;
    private int abc1=1;
    private int abc2=1;

    public ABC() {
    }

    public int getAbc() {
        return abc;
    }

    public void setAbc(int abc) {
        this.abc = abc;
    }

    public int getAbc1() {
        return abc1;
    }

    public void setAbc1(int abc1) {
        this.abc1 = abc1;
    }

    public int getAbc2() {
        return abc2;
    }

    public void setAbc2(int abc2) {
        this.abc2 = abc2;
    }
}

import java.awt.*;
import java.util.Random;

public class Close {
    public static void main(String[] args) {
        for(int i=0;i<=10;i++){
            System.out.println(close());
        }
    }


    public static String close()
    {
        //红色
        String red;
        //绿色
        String green;
        //蓝色
        String blue;
        //生成随机对象
        Random random = new Random();
        //生成红色颜色代码
        red = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成绿色颜色代码
        green = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成蓝色颜色代码
        blue = Integer.toHexString(random.nextInt(256)).toUpperCase();

        //判断红色代码的位数
        red = red.length()==1 ? "0" + red : red ;
        //判断绿色代码的位数
        green = green.length()==1 ? "0" + green : green ;
        //判断蓝色代码的位数
        blue = blue.length()==1 ? "0" + blue : blue ;
        //生成十六进制颜色值
        String color = "#"+red+green+blue;

        System.out.println(color);

        return  color;
    }

}


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String getHtmlByPost(String urlString,String postBody) throws IOException {
        byte[] xmlData = postBody.getBytes();
        //接收想要连接网址的地址
        URL url=new URL(urlString);
        //响应
        StringBuilder responseBuilder=new StringBuilder();
        //读取信息为文本信息,所以用bufferReader
        BufferedReader reader=null;
        //用url对象打开连接(仅仅打开了连接,并未发送请求)
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
        //设置HttpURLConnection参数
        //设置post方法
        conn.setRequestMethod("POST");
        //不使用缓存
        conn.setUseCaches(false);
        conn.setDefaultUseCaches(false);
        //post请求必须设置如下2行
        conn.setDoInput(true);
        conn.setDoOutput(true);
        //读取超时时间
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        //设置不要302自动跳转,防止重定向
        conn.setInstanceFollowRedirects(false);
        //设置传入参数的格式
        conn.setRequestProperty("Content-Type","application/json");
        //没写可能出现411错误
        conn.setRequestProperty("Content-Length",String.valueOf(xmlData.length));
        //通过连接对象获取一个输出流
        DataOutputStream printout = new DataOutputStream(conn.getOutputStream());
        //输出流发送请求参数
        printout.write(xmlData);
        //flush输出流的缓冲
        printout.flush();
        printout.close();

        //定义BufferedReader输入流来读取URL的响应

        int code=conn.getResponseCode();
        System.out.println(code);

        if(code==200) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            //逐行读取数据
            String line = null;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line + "\n");
            }
            reader.close();
        }else{
            conn.getErrorStream();
        }
        String result=responseBuilder.toString();
        return  result;
    }

}

public class WeChatTemplateMsg {
    /**
     * 消息
     */
    private String value;
    /**
     * 消息颜色
     */
    private String color;


    public WeChatTemplateMsg(String value) {
        this.value = value;
        this.color = "#173177";
    }

    public WeChatTemplateMsg(String value, String color) {
        this.value = value;
        this.color = color;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import org.thymeleaf.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class Yi {
    String accessToken;
    public static void main(String[] args) throws Exception {


        Yi y=new Yi();
        String appid="wx122f233fcadb27ccxxxx"; //对应的id
        String secret="xxxx"; //对应秘钥 就是上面那个appid下面那个
        Connection.Response document = Jsoup.connect("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+"").timeout(4000).userAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.15").ignoreContentType(true).execute();
        Document parse = document.parse();
        String parse1 = String.valueOf(parse);
        String access = StringUtils.substringBefore(StringUtils.substringAfter(parse1, "access_token\":\""), "\",\"expires_in");
        y.accessToken=access; //获取
//        System.out.println(access);
        y.sendMessage();

    }

    public  void sendMessage() {
        // 模板参数
        Map<String, WeChatTemplateMsg> sendMag = new HashMap<>();

        // openId代表一个唯一微信用户,即微信消息的接收人
        String openId = "o565j6tLmAwhVMhY1UIG7ipgaNvc";
        // 公众号的模板id(也有相应的接口可以查询到)
        String templateId = "oXOvDQYxGmt4MBJWYJRPZvSDgKxP4Atip6bHKs-mOuM";
        // 微信的基础accessToken

        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;




        sendMag.put("d1", new WeChatTemplateMsg("哈哈哈嗯嗯","#28AEBD"));
//        sendMag.put("keyword1", new WeChatTemplateMsg("111"));


        //拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        sendBody.put("touser", openId);               // openId
        sendBody.put("url", "www.baidu.com");         // 点击模板信息跳转地址
        sendBody.put("topcolor", Close.close());          // 顶色
        sendBody.put("data", sendMag);                   // 模板参数



        sendBody.put("template_id", templateId);      // 模板Id

        JSONObject json = new JSONObject(sendBody);
//        System.out.println(url+json);




        try{
            System.out.println(Main.getHtmlByPost(url, String.valueOf(json)));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

游迹AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值