JAVA微信公众号开发之自动回复消息与图片

首先,应该建立一个消息与图片的实体,看一下微信公众号的文档:

 

回复文本消息

<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[fromUser]]></FromUserName>

<CreateTime>12345678</CreateTime>

<MsgType><![CDATA[text]]></MsgType>

<Content><![CDATA[你好]]></Content>

</xml>

 

 

参数是否必须描述
ToUserName接收方帐号(收到的OpenID)
FromUserName开发者微信号
CreateTime消息创建时间 (整型)
MsgTypetext
Content回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)

回复图片消息

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[media_id]]></MediaId>
</Image>
</xml>

 

参数是否必须说明
ToUserName接收方帐号(收到的OpenID)
FromUserName开发者微信号
CreateTime消息创建时间 (整型)
MsgTypeimage
MediaId

通过素材管理中的接口上传多媒体文件,得到的id。

 

 

之后组装实体,用户发来消息或者事件时候给微信服务器发送请求,服务器把消息返回给在公众号配置的服务器域名处,然后再进行逻辑判断,给微信服务器返回消息,发给用户。

 

下面给出一般的消息类型:

        public static final String MESSAGE_SCAN="SCAN";//未关注公众号扫描二维码
public static final String MESSAGE_TEXT="text";//文本
public static final String MESSAGE_IMAGE="image";//图片
public static final String MESSAGE_VOICE="voice";//语音
public static final String MESSAGE_VIDEO="video";//视频
public static final String MESSAGE_LINK="link";//连接
public static final String MESSAGE_LOCATION="location";//地理位置事件
public static final String MESSAGE_EVENT="event";//事件
public static final String MESSAGE_SUBSCRIBE="subscribe";//关注
public static final String MESSAGE_UNSUBSCRIBE="unsubscribe";//取消关注
public static final String MESSAGE_CLICK="CLICK";//点击
public static final String MESSAGE_VIEW="VIEW";//t跳转链接url

需要注意的是,发送图片需要先把图片上传到微信服务器获取MediaId,才能发给用户。

 

/**
	 * xml转为map集合
	 * @MethodName:xmlToMap
	 *@author:maliran
	 *@ReturnType:Map<String,String>
	 *@param req
	 *@return
	 *@throws IOException
	 *@throws DocumentException
	 */
	public static Map<String,String> xmlToMap(HttpServletRequest req) throws IOException, DocumentException{
		
		Map<String,String> map = new HashMap<String,String>();
		SAXReader reader = new SAXReader();//log4j.jar
		InputStream ins = req.getInputStream();
		Document doc = reader.read(ins);
		Element root = doc.getRootElement();
		List<Element> list = root.elements();
		for(Element e:list){
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}
	/**
	 * 文本转换为xml
	 * @MethodName:textMessageToXml
	 *@author:maliran
	 *@ReturnType:String
	 *@param textMessage
	 *@return
	 */
	public static String textMessageToXml(TextMessage textMessage){
		
		XStream xstream = new XStream();//xstream.jar,xmlpull.jar
		xstream.alias("xml", textMessage.getClass());//置换根节点
		System.out.println(xstream.toXML(textMessage));
		return xstream.toXML(textMessage);
		
	}
	/**
	 * 图片转成xml
	 * @MethodName:textMessageToXml
	 *@author:maliran
	 *@ReturnType:String
	 *@param textMessage
	 *@return
	 */
    public static String imageMessageToXml(ImageMessage imageMessage){
		
		XStream xstream = new XStream();//xstream.jar,xmlpull.jar
		xstream.alias("xml", imageMessage.getClass());//置换根节点
		//System.out.println(xstream.toXML(imageMessage));
		return xstream.toXML(imageMessage);
		
	}
	
    /**
     * 组装图片xml
     * @MethodName:initImageMessage
     *@author:maliran
     *@ReturnType:String
     *@param MediaId
     *@param toUserName
     *@param fromUserName
     *@return
     */
	public static String initImageMessage(String MediaId,String toUserName,String fromUserName){		
		String message = null;
		Image image = new Image();
		ImageMessage imageMessage = new ImageMessage();
		image.setMediaId(MediaId);
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setCreateTime(new Date().toString());
		imageMessage.setImage(image);
		imageMessage.setMsgType(MESSAGE_IMAGE);
		message = imageMessageToXml(imageMessage);
		return message;
	}
	public static String initTextMessage(String content,String toUserName,String fromUserName){		
		String message = null;
		TextMessage textMessage = new TextMessage();
		textMessage.setFromUserName(toUserName);
		textMessage.setToUserName(fromUserName);
		textMessage.setCreateTime(new Date().toString());
		textMessage.setContent(content);
		textMessage.setMsgType(MESSAGE_TEXT);
		message = textMessageToXml(textMessage);
		return message;
	}
/**
	 * 上传本地文件到微信获取mediaId
	 */
	
	public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}

		String url = ConfigUtil.UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
		
		URL urlObj = new URL(url);
		//连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		con.setRequestMethod("POST"); 
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); 

		//设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		//设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");

		//获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		//输出表头
		out.write(head);

		//文件正文部分
		//把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		//结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线

		out.write(foot);

		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		try {
			//定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		JSONObject jsonObj = JSONObject.fromObject(result);
		System.out.println(jsonObj);
		String typeName = "media_id";
		if(!"image".equals(type)){
			typeName = type + "_media_id";
		}
		String mediaId = jsonObj.getString(typeName);
		return mediaId;
	}

 

public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
	req.setCharacterEncoding("UTF-8");
	resp.setCharacterEncoding("UTF-8");
	String serverPath="";
	serverPath = req.getServletContext().getRealPath("/").replace("\\", "/");  
    //Servlet初始化时执行,如果上传文件目录不存在则自动创建  
    if(!new File(serverPath+"qrimage").isDirectory()){  
        new File(serverPath+"qrimage").mkdirs();  
    }   
	PrintWriter out = resp.getWriter();
	
	//String openId = GetCookie.getCookie(req,resp);
		Map<String, String> map;
		try {
			map = MessageUtil.xmlToMap(req);
		String fromUserName = map.get("FromUserName");
		System.out.println(fromUserName);
		String toUserName = map.get("ToUserName");
		
		 String msgType = map.get("MsgType");
		//String content = map.get("Content");
		
		 String message = "";
		 if(MessageUtil.MESSAGE_EVENT.equals(msgType)){		 
			 System.out.println("事件");
			 String eventType = map.get("Event");
			 System.out.println(eventType);
			 String eventKey = map.get("EventKey");
			 System.out.println(map.get("EventKey"));
				 if(MessageUtil.MESSAGE_CLICK.equals(eventType)){
				String key = map.get("EventKey");
				if(key.equals("1")){
				String filePath = serverPath+"qrimage"+"\\"+fromUserName+".jpg";  
				//String url = "WebContent/qrimage/"+fromUserName+".jpg";
				String ticket = wxQRCodeService.createForeverStrTicket(fromUserName);	 
		
			    //System.out.println(url);
			    //获取access_token				
                                      String content = "123456";
                                    String mediaId = MyImageUtil.upload(filePath, accessToken,MessageUtil.MESSAGE_IMAGE);
			         String imageMessage = MessageUtil.initImageMessage(mediaId, toUserName, fromUserName);
	   
			        System.out.println(imageMessage);
			       
			        out.print(imageMessage);
					out.close();
					
					
			    }}
			   
		}else{
			return;	
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
}	

 

 

最近在整理一些资源工具,放在网站分享 http://tools.maqway.com
欢迎关注公众号:麻雀唯伊 , 不定时更新资源文章,生活优惠,或许有你想看的

 

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
您好!关于Java微信公众号开发,我可以为您提供一些基本的信息和指导。 首先,微信公众号开发要有两种类型:订阅号和服务号。订阅号主要用于信息传达和内容分享,而服务号则更加注重业务功能和用户交互。 在Java开发中,您可以使用微信公众平台提供的开发接口进行开发。以下是一些常用的开发步骤和技术: 1. 注册微信公众平台账号:前往微信公众平台(https://mp.weixin.qq.com/)注册一个账号,并完成开发者认证。 2. 配置服务器:在公众号设置中,配置服务器URL和Token。Token用于验证消息的真实性。 3. 接入消息接口:通过开发接口,将用户发送的消息和事件推送到您的服务器。您可以使用Java框架(如Spring Boot)搭建服务器,并使用接口进行消息的处理和回复。 4. 实现功能:根据您的需求,可以实现一些常见的功能,如自动回复、菜单管理、用户管理、消息模板等。您可以使用Java的相关库和工具来简化开发过程。 5. 公众号运营:在开发完成后,可以进行公众号的运营和推广。您可以通过素材管理、群发消息、数据统计等功能来提升用户体验和运营效果。 需要注意的是,微信公众号开发涉及到用户隐私和信息安全,建议您在开发过程中遵守相关规定,并进行必要的数据加密和安全防护。 希望以上信息对您有所帮助!如果您有任何进一步的问题,请随时提问。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值