【开发管理】【开发设置】【消息推送】---开发者服务器接收消息推送

点击启用的时候 会出现会填写服务器地址之类的信息,填写之后点击提交,会向填写的服务器地址发送get请求校验通过后才能成功启用。

当时开发的时候就想,这个接口用来校验,但是这个接口也要用来接收消息体,要求返回的参数也不一致,怎么区分呢?

后来想到通过get和post请求参数的不同来区分是校验逻辑还是消息逻辑。(或许也可以是上线之前只写校验逻辑,提交通过校验后再改正,我没有用这种方法,不知道正不正确。)

附上我的源码

public void getWechatBackInfo(HttpServletRequest request, HttpServletResponse response) {
		String echostr = request.getParameter("echostr");
		//校验处理
		if (echostr != null && (echostr.length()) != 0) {
			PrintWriter out = null;
			try {
				//TODO 省略校验逻辑,当校验成功时返回echostr字段
				out = response.getWriter();
				out.print(echostr);
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				out.close();
			}
			return;
		}
		
		//正常处理
		try {
			StringBuffer str = new StringBuffer();
			InputStreamReader reader=new InputStreamReader(request.getInputStream(),"UTF-8");
			char [] buff=new char[1024];
			int length=0;
			while((length=reader.read(buff))!=-1){
				String x=new String(buff,0,length);
				str.append(x);
			}
			String jsonstr = str.toString();
			//TODO jsonstr就是微信参数的json串 
			//TODO 省略处理消息体的代码
		}catch (Exception e){
		}

		//不返回报错 报错只记录在日志中,所有情况都默认为成功
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print("success");
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

ps:不知道我这样配置是不是走了弯路,但是启用成功也接收到消息了,如果有大佬路过的话希望能指正!

更多推荐