-
Notifications
You must be signed in to change notification settings - Fork 446
如何使用Server
jinyu edited this page May 9, 2016
·
3 revisions
weixin4j-server可单独作为一个服务启动,用于处理微信的被动消息,即用户主动发送给公众号的消息、系统通知等消息
###编写服务启动类 明文模式并总是调试输出微信请求信息的服务启动类.
public class MessageServerStartup{
public static void main(String[] args) {
new WeixinServerBootstrap("token").addHandler(
DebugMessageHandler.global).startup();
}
}
密文模式的服务启动类
public class MessageServerStartup{
public static void main(String[] args) {
new WeixinServerBootstrap("appid/corpid","token","aesKey").addHandler(
DebugMessageHandler.global).startup();
}
}
只针对文本消息的服务启动类
public class MessageServerStartup{
public static void main(String[] args) {
// 针对文本消息回复
WeixinMessageHandler messageHandler = new MessageHandlerAdapter<TextMessage>() {
@Override
public WeixinResponse doHandle0(WeixinRequest request,
TextMessage message) throws WeixinException {
return new TextResponse("HelloWorld!");
}
};
// 当消息类型为文本(text)时回复「HelloWorld」, 否则回复调试消息
new WeixinServerBootstrap(appid, token, aesKey).addHandler(
messageHandler, DebugMessageHandler.global).startup();
}
}
}
使用拦截器处理消息请求的启动类
public static void main(String[] args) {
// 拦截所有请求
WeixinMessageInterceptor interceptor = new MessageInterceptorAdapter() {
@Override
public boolean preHandle(ChannelHandlerContext context,
WeixinRequest request, WeixinResponse response, Object message,
WeixinMessageHandler handler) throws WeixinException {
context.write(new TextResponse("所有消息被拦截了!"));
return false;
}
@Override
public void postHandle(ChannelHandlerContext context,
WeixinRequest request, WeixinResponse response, WeixinResponse response,
Object message, WeixinMessageHandler handler)
throws WeixinException {
System.err.println("preHandle返回为true,执行handler后");
}
@Override
public void afterCompletion(ChannelHandlerContext context,
WeixinRequest request, WeixinResponse response, Object message,
WeixinMessageHandler handler, WeixinException exception)
throws WeixinException {
System.err.println("请求处理完毕");
}
};
new WeixinServerBootstrap("token").addInterceptor(interceptor)
.addHandler(BlankMessageHandler.global).startup();
}
扫描下图二维码进行体验
- 关注时回复「欢迎关注~」SubscribeMessageHandler
- 输入任意文本时回复「收到了文本消息」TextMessageHandler
- 输入「hello」文本时回复「world」HelloMessageHandler
- 发送语音消息时回复「你讲了一句话」VoiceMessageHandler
- 其它消息则回复调试信息DebugMessageHandler