JavaWeb发送信息到微信公众平台的企业号

2023-12-04 01:48

本文主要是介绍JavaWeb发送信息到微信公众平台的企业号,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

首先到微信公众平台申请微信企业号: https://qy.weixin.qq.com
申请后需要在管理平台做如下几个步骤:
1、在通讯录里添加一个成员并使这个成员关注这个微信企业号;
2、在应用中心里新建一个应用并记录appid;
3、在设置里的权限管理中新建管理组;


新建一个JavaWeb工程并导入如下几个jar文件:
commons-logging-1.1.1.jar,fastjson-1.2.7.jar,httpclient-4.5.1.jar,httpcore-4.4.3.jar,weixin-java-cp-1.3.1.jar

下载jquery-2.1.4.min.js文件并添加到JavaWeb工程中。

JavaWeb工程的代码如下:

AccessToken.java文件内容如下:

package com.shihuan.pojo;

import java.io.Serializable;

public class AccessToken implements Serializable {

private String access_token;
private String expires_in;

public AccessToken() {

}

public String getAccess_token() {
return access_token;
}

public void setAccess_token(String accessToken) {
access_token = accessToken;
}

public String getExpires_in() {
return expires_in;
}

public void setExpires_in(String expiresIn) {
expires_in = expiresIn;
}

}


Text.java文件内容如下:

package com.shihuan.pojo;

import java.io.Serializable;

public class Text implements Serializable {

private String content;

public Text() {

}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}


MsgTypeAndDataFormat.java文件内容如下:

package com.shihuan.pojo;

import java.io.Serializable;

public class MsgTypeAndDataFormat implements Serializable {

private String touser;
private String toparty;
private String totag;
private String msgtype;
private String agentid;
private Text text;
private String safe;

public MsgTypeAndDataFormat() {

}

public String getTouser() {
return touser;
}

public void setTouser(String touser) {
this.touser = touser;
}

public String getToparty() {
return toparty;
}

public void setToparty(String toparty) {
this.toparty = toparty;
}

public String getTotag() {
return totag;
}

public void setTotag(String totag) {
this.totag = totag;
}

public String getMsgtype() {
return msgtype;
}

public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}

public String getAgentid() {
return agentid;
}

public void setAgentid(String agentid) {
this.agentid = agentid;
}

public Text getText() {
return text;
}

public void setText(Text text) {
this.text = text;
}

public String getSafe() {
return safe;
}

public void setSafe(String safe) {
this.safe = safe;
}

}


WeixinCpServlet.java文件内容如下:

package com.shihuan.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.shihuan.pojo.AccessToken;
import com.shihuan.pojo.MsgTypeAndDataFormat;
import com.shihuan.pojo.Text;

public class WeixinCpServlet extends HttpServlet {

protected void doGet(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) throws ServletException, IOException {
System.out.println("doGet...");
paramHttpServletResponse.getWriter().write("WeixinCp doGet!");
paramHttpServletResponse.flushBuffer();
System.out.println("doGet...");
}

protected void doPost(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse) throws ServletException, IOException {
System.out.println("doPost...");

String corpid = paramHttpServletRequest.getParameter("corpid");
String corpsecret = paramHttpServletRequest.getParameter("corpsecret");
StringBuilder sb = new StringBuilder();
sb.append("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=").append(corpid).append("&corpsecret=").append(corpsecret);
String getTokenUrl = sb.toString();
HttpPost getTokenUrlPost = new HttpPost(getTokenUrl);
DefaultHttpClient getTokenUrlClient = new DefaultHttpClient();
HttpResponse getTokenUrlResponse = getTokenUrlClient.execute(getTokenUrlPost);
AccessToken atentry = new AccessToken();
if (getTokenUrlResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = getTokenUrlResponse.getEntity();
String jsontext = EntityUtils.toString(entity, "utf-8");
System.out.println(jsontext);
atentry = (AccessToken) JSON.parseObject(jsontext, AccessToken.class);
}

String access_token = atentry.getAccess_token();
System.out.println(access_token);
StringBuilder sbsend = new StringBuilder();
sbsend.append("https://qyapi.weixin.qq.com/cgi-bin/message/send?body=0&access_token=").append(access_token);
String url = sbsend.toString();

String jsonbody = paramHttpServletRequest.getParameter("jsonbody");

Text t = new Text();
t.setContent(jsonbody);

MsgTypeAndDataFormat m = new MsgTypeAndDataFormat();
m.setAgentid("2");
m.setMsgtype("text");
m.setSafe("0");
m.setText(t);
m.setToparty("@all");
m.setTotag("@all");
m.setTouser("@all");

String json = JSON.toJSONString(m);

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);

HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
System.out.println(EntityUtils.toString(entity, "utf-8"));
}

System.out.println("doPost...");
}

public void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse) throws ServletException,IOException {
System.out.println("WeixinCpService...");
super.service(paramServletRequest, paramServletResponse);
paramServletResponse.getWriter().write("WeixinCp service!");
System.out.println("WeixinCpService...");
}

public void init(ServletConfig paramServletConfig) throws ServletException {
super.init(paramServletConfig);
System.out.println("WeixinCpServlet...");
}

public void destroy() {
System.out.println("WeixinServlet[destroy]...");
super.destroy();
}

}


web.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>WeixinCp</display-name>

<servlet>
<servlet-name>WeixinCpServlet</servlet-name>
<servlet-class>com.shihuan.servlet.WeixinCpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WeixinCpServlet</servlet-name>
<url-pattern>/weixincp</url-pattern>
</servlet-mapping>


<session-config>
<session-timeout>60</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>


index.html文件内容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>weixincp servlet</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
function sendWxMsg(){
var url = "weixincp";
$.post(url, {corpid:$("#corpid").val(),corpsecret:$("#corpsecret").val(),jsonbody:$("#jsonbody").val()});
}
</script>
</head>

<body>
<form name="frm_data" id="frm_data" method="POST" action="weixincp">
corpid: <input type="text" id="corpid" name="corpid" value="" size="80px" /><br />
corpsecret: <input type="text" id="corpsecret" name="corpsecret" value="" size="80px" /><br />
content: <input type="text" id="jsonbody" name="jsonbody" value="" size="80px" /><br /><br />
<input type="button" id="sendbtn" name="sendbtn" value="sendWxMsg" onclick="sendWxMsg();" />
</form>
</body>
</html>



【[color=blue]注[/color]】:附件中是可运行源代码, :arrow:

这篇关于JavaWeb发送信息到微信公众平台的企业号的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/451659

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映