国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet WeChat Development WeChat secondary development text message request and sending

WeChat secondary development text message request and sending

May 10, 2017 am 09:25 AM
java WeChat

This article mainly introduces the second part of Java WeChat secondary development in detail, the request and sending function of Java WeChat text message interface, which has certain reference value. Interested friends can refer to it

The second article, making WeChat text message interface request and send, the specific content is as follows

Requires import library: dom4j-1.6.1.jar, xstream-1.3.1.jar

The first step: Create a new package com.wtz.message.response and create a new class BaseMessage.java

package com.wtz.message.response;

/**
 * @author wangtianze QQ:864620012
 * @date 2017年4月19日 下午3:12:40
 * <p>version:1.0</p>
 * <p>description:基礎(chǔ)消息類</p>
 */
public class BaseMessage {
 //接收方
 private String ToUserName;
 //發(fā)送方
 private String FromUserName;
 //消息的創(chuàng)建時(shí)間
 private long CreateTime;
 //消息類型
 private String MsgType;
 
 public String getToUserName() {
 return ToUserName;
 }
 public void setToUserName(String toUserName) {
 ToUserName = toUserName;
 }
 public String getFromUserName() {
 return FromUserName;
 }
 public void setFromUserName(String fromUserName) {
 FromUserName = fromUserName;
 }
 public long getCreateTime() {
 return CreateTime;
 }
 public void setCreateTime(long createTime) {
 CreateTime = createTime;
 }
 public String getMsgType() {
 return MsgType;
 }
 public void setMsgType(String msgType) {
 MsgType = msgType;
 }
}

The second step: Find the package com.wtz.message.response , create a new class TextMessage.java

package com.wtz.message.response;

/**
 *  @author wangtianze QQ:864620012
 * @date 2017年4月19日 下午3:22:33
 * <p>version:1.0</p>
 *  <p>description:文本消息類</p>
 */
public class TextMessage extends BaseMessage{
 //消息內(nèi)容
 private String Content;
 
 public String getContent() {
  return Content;
 }
 public void setContent(String content) {
  Content = content;
 }
}

The third step:Find the package com.wtz.util, create a new class MessageUtil.java

package com.wtz.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.wtz.message.response.TextMessage;

/**
 *  @author wangtianze QQ:864620012
 * @date 2017年4月19日 下午3:29:58
 * <p>version:1.0</p>
 *  <p>description:消息處理工具類</p>
 */
public class MessageUtil {
 //定義了消息類型(常量:文本類型)
 public static final String RESP_MESSAGE_TYPE_TEXT = "text";
 
 //從流中解析出每個節(jié)點(diǎn)的內(nèi)容
 public static Map<String,String> parseXml(HttpServletRequest request) throws IOException{
  Map<String,String> map = new HashMap<String,String>();
  
  //從輸入流中獲取流對象
  InputStream in = request.getInputStream();
  
  //構(gòu)建SAX閱讀器對象
  SAXReader reader = new SAXReader();
  try {
   //從流中獲得文檔對象
   Document doc = reader.read(in);
   
   //獲得根節(jié)點(diǎn)
   Element root = doc.getRootElement();
   
   //獲取根節(jié)點(diǎn)下的所有子節(jié)點(diǎn)
   List<Element> children = root.elements();
   
   for(Element e:children){
    //遍歷每一個節(jié)點(diǎn),并按照節(jié)點(diǎn)名--節(jié)點(diǎn)值放入map中
    map.put(e.getName(), e.getText());
    System.out.println("用戶發(fā)送的消息XML解析為:" + e.getName() + e.getText());
   }
   
   //關(guān)閉流
   in.close();
   in = null;
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return map;
 }
 
 /**
  * 用于擴(kuò)展節(jié)點(diǎn)數(shù)據(jù)按照<ToUserName><![CDATA[toUser]]></ToUserName>,中間加了CDATA段
  */
 private static XStream xstream = new XStream(new XppDriver(){
  public HierarchicalStreamWriter createWriter(Writer out){
   return new PrettyPrintWriter(out){
    boolean cdata = true;
    public void startNode(String name,Class clazz){
     super.startNode(name,clazz);
    }
    
    protected void writeText(QuickWriter writer,String text){
     if(cdata){
      writer.write("<![CDATA[");
      writer.write(text);
      writer.write("]]>");
     }else{
      writer.write(text);
     }
    }
   };
  }
 });
 
 /**
  * 將文本消息轉(zhuǎn)換成XML格式
  */
 public static String messageToXml(TextMessage textMessage){
  xstream.alias("xml",textMessage.getClass());
  String xml = xstream.toXML(textMessage);
  System.out.println("響應(yīng)所轉(zhuǎn)換的XML:"+xml);
  return xml;
 }
}

The fourth step: Find the package com.wtz.service and create a new class ProcessService.java

package com.wtz.util;

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

import javax.servlet.http.HttpServletRequest;

import com.wtz.message.response.TextMessage;

/**
 *  @author wangtianze QQ:864620012
 * @date 2017年4月19日 下午8:04:14
 * <p>version:1.0</p>
 *  <p>description:核心服務(wù)類</p>
 */
public class ProcessService {
 public static String dealRequest(HttpServletRequest request) throws IOException{
  //響應(yīng)的XML串
  String respXml = "";
  
  //要響應(yīng)的文本內(nèi)容
  String respContent = "未知的消息類型";
  Map<String,String> requestMap = MessageUtil.parseXml(request);
  String fromUserName = requestMap.get("FromUserName");
  String toUserName = requestMap.get("ToUserName");
  String MsgType = requestMap.get("MsgType");
  String Content = requestMap.get("Content");
  
  System.out.println("用戶給公眾號發(fā)的消息為:" + Content);
  
  //構(gòu)建一條文本消息
  TextMessage textMessage = new TextMessage();
  textMessage.setToUserName(fromUserName);
  textMessage.setFromUserName(toUserName);
  textMessage.setCreateTime(new Date().getTime());
  textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
  
  if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)){
   respContent = "王天澤的公眾號收到了您的一條文本消息:" + Content + ",時(shí)間戳是:" + (new Date().getTime());
  }
  textMessage.setContent(respContent);
  respXml = MessageUtil.messageToXml(textMessage);
  
  System.out.println("respXml:"+respXml);
  
  return respXml;
 }
}

Step 5: Find the LoginServlet class under the package com.wtz.service and rewrite the doPost method

package com.wtz.service;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wtz.util.MessageUtil;
import com.wtz.util.ProcessService;
import com.wtz.util.ValidationUtil;

/**
 *  @author wangtianze QQ:864620012
 * @date 2017年4月17日 下午8:11:32
 * <p>version:1.0</p>
 *  <p>description:微信請求驗(yàn)證類</p>
 */
public class LoginServlet extends HttpServlet {

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  System.out.println("get請求。。。。。。");
  
  //1.獲得微信簽名的加密字符串
  String signature = request.getParameter("signature");
  
  //2.獲得時(shí)間戳信息
  String timestamp = request.getParameter("timestamp");
   
  //3.獲得隨機(jī)數(shù)
  String nonce = request.getParameter("nonce");
  
  //4.獲得隨機(jī)字符串
  String echostr = request.getParameter("echostr");
  
  System.out.println("獲得微信簽名的加密字符串:"+signature);
  System.out.println("獲得時(shí)間戳信息:"+timestamp);
  System.out.println("獲得隨機(jī)數(shù):"+nonce);
  System.out.println("獲得隨機(jī)字符串:"+echostr);
  
  PrintWriter out = response.getWriter();
  
  //驗(yàn)證請求確認(rèn)成功原樣返回echostr參數(shù)內(nèi)容,則接入生效,成為開發(fā)者成功,否則失敗
  if(ValidationUtil.checkSignature(signature, timestamp, nonce)){
   out.print(echostr);
  }
  
  out.close();
  out = null;
 }

 /**
  * 接受微信服務(wù)器發(fā)過來的XML數(shù)據(jù)包(通過post請求發(fā)送過來的)
  */
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  request.setCharacterEncoding("utf-8");
  response.setCharacterEncoding("utf-8");
  
  //獲取微信加密的簽名字符串
  String signature = request.getParameter("signature");
  
  //獲取時(shí)間戳
  String timestamp = request.getParameter("timestamp");
  
  //獲取隨機(jī)數(shù)
  String nonce = request.getParameter("nonce");
  
  PrintWriter out = response.getWriter();
  
  if(ValidationUtil.checkSignature(signature,timestamp,nonce)){
   String respXml = "";
   try {
    respXml = ProcessService.dealRequest(request);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   out.print(respXml);
  }
  out.close();
  out = null;
 }
}

Complete WeChat text message interface request and sending.

【Related recommendations】

1. WeChat public account platform source code download

2. WeChat voting source code

The above is the detailed content of WeChat secondary development text message request and sending. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Building RESTful APIs in Java with Jakarta EE Building RESTful APIs in Java with Jakarta EE Jul 30, 2025 am 03:05 AM

SetupaMaven/GradleprojectwithJAX-RSdependencieslikeJersey;2.CreateaRESTresourceusingannotationssuchas@Pathand@GET;3.ConfiguretheapplicationviaApplicationsubclassorweb.xml;4.AddJacksonforJSONbindingbyincludingjersey-media-json-jackson;5.DeploytoaJakar

css dark mode toggle example css dark mode toggle example Jul 30, 2025 am 05:28 AM

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

css dropdown menu example css dropdown menu example Jul 30, 2025 am 05:36 AM

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

python parse date string example python parse date string example Jul 30, 2025 am 03:32 AM

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Where to download Ouyi? Where to download Ouyi safely? Where to download Ouyi? Where to download Ouyi safely? Jul 30, 2025 pm 06:57 PM

The safest way to obtain Ouyi applications is to use its official website, carefully check the domain name to prevent phishing websites; 2. The official website will automatically identify the device type and provide corresponding download options. Apple users can search and download on the App Store. Android users can use Google Play or official website links to download it first; 3. Do not click on unknown links such as text messages, social groups, etc., and refuse installation files shared by third-party markets or individuals; 4. The latest website information can be verified through official certified social media; 5. Android users need to temporarily enable the "Allow to install applications from unknown sources" permission, and should be closed immediately after installation to ensure safety. Always downloading through official channels is a key measure to protect the security of digital assets.

css full page layout example css full page layout example Jul 30, 2025 am 05:39 AM

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Full-Stack Web Development with Java, Spring Boot, and React Full-Stack Web Development with Java, Spring Boot, and React Jul 31, 2025 am 03:33 AM

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter

See all articles