위챗 공식 계정 개발 모델 순수 JSP 코드

11183 단어
%@ page import="java.net.*"% %@ page import="java.math.*"% %@ page import="java.io.*"% %@ page import="java.text.*"% %@page import="java.util.Date"% %@page import="org.dom4j.Element"% %@page import="org.dom4j.DocumentHelper"% %@page import="org.dom4j.Document"% %@page import="java.io.IOException"% %@page import="java.io.InputStreamReader"% %@page import="java.io.BufferedReader"% %@page import="java.io.Reader"% %@page import="java.security.MessageDigest"% %@page import="java.util.Arrays"% %@page import="java.util.ArrayList"% %@page import="java.util.Collections"% %@page import="java.util.List"% %@page import="java.util.regex.Matcher"% %@page import="java.util.regex.Pattern"%
%@ page language = "java"contentType = "text/html;charset=utf-8"pageEncoding = "utf-8"% <%//WeiXinHandler는 내부 클래스에final 형식이 아닌 대상을 사용할 수 없습니다
final String TOKEN=“daniuco”;//여기에 자신의 TOKEN 매개 변수를 입력하십시오. 개발 모드final HttpServletRequest finalrequest=request; final HttpServletResponse final_response=response; %>
<% class WeiXinHandler{ public void valid(){ String echostr=final_request.getParameter(“echostr”); if(null==echostr||echostr.isEmpty()) {
 responseMsg(); 

}else{
  if(this.checkSignature())
  {
     this.print(echostr); 
  }else{ 
     this.print("error");  
  } 
  }

}
//자동 응답 콘텐츠 public void responseMsg()
{
String postStr=null;
try{ 
    postStr=this.readStreamParameter(final_request.getInputStream()); 
    //System.out.print(postStr);


}catch(Exception e)
{ e.printStackTrace(); } 
    //System.out.println(postStr);

if (null!=postStr&&!postStr.isEmpty()) { Document document=null; try{
document = DocumentHelper.parseText(postStr); 

}catch(Exception e){ e.printStackTrace(); }
if(null==document) { this.print(““); return; }
Element root=document.getRootElement(); String fromUsername = root.elementText(“FromUserName”); String toUsername = root.elementText(“ToUserName”); String keyword = root.elementTextTrim(“Content”); long longTime = new Date().getTime(); String time = longTime/1000 +““; String msgType = root.elementText(“MsgType”); String event = root.elementText(“Event”);
String textTpl = ““+ “%1$s “+ “%2$s “+ “%3$s “+ “%4$s “+ “%5$s “+ “0 “+ ““;
String htmlTpl = ““+ “%1$s “+ “%2$s “+ “%3$s “+ “%4$s ” +
     "[%5$s]" + "</Articles></xml>"; 

//공용 도움말 문서String helpHtml = "언제든지"help"또는"도움말"또는"?"삼자 중 하나가 최신 사용 매뉴얼을 얻는다.분류 정보([c:뉴스], [c:공고], [c:연보] 등) 역사 정보([2013-10-05]: 어느 날 정보, [d:9]: 지난 9일 동안의 정보, [d:-9]: 지난 9일 전의 정보, 기본 조회 범위 10일 이내)"
if(null!=msgType && !msgType.equals(““)) {
 /**
  *    
  */

if(msgType.equals(“event”) && event.equals(“subscribe”)) {
 //  
  String subscribeHtml = "";
  msgType = "news";

  //String helpHtml  =  "
, \"help\" \" \" 。
(c: ,c: ,c: )
([2013-10-05]: ,[d:9]: 9 ,[d:-9]: 9 , 10 )"; String helpPicUrl = "http://www.daniu.co/images/weixin/finance_travel_640_320.jpg"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[ ]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA[" + helpContentUrl + "]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; subscribeHtml = helpResults; //System.out.println(subscribeHtml); String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, subscribeHtml); this.print(resultStr);

}
if(msgType.equals(“event”) && event.equals(“unsubscribe”)) {
 //  
  String subscribeHtml = "";
  msgType = "news";

  helpHtml  =  "
daniuco

, , ... ..."; String helpPicUrl = "http://www.daniu.co/images/weixin/finance_640_320.png"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[ ]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA[" + helpContentUrl + "]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; subscribeHtml = helpResults; //System.out.println(subscribeHtml); String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, subscribeHtml); this.print(resultStr);

}
}
if(null!=keyword&&!keyword.equals(““)) {
/** 답장 텍스트 정보
String msgType = “text”;
String contentStr = "시스템은 개발 과정에서 기대하십시오!", if(keyword.equals("help")|||keyword.equals(도움말){//사용 설명서
  contentStr = contentStr + "
, , \"help\" \" \" 。";

}//Autonomy Search contentStr = contentStr + "= = = 자동 푸시 테스트 내용 = = ="+ Autonomy Search (keyword)
String resultStr = textTpl.format(textTpl, fromUsername, toUsername, time, msgType, contentStr);
/* 답장 텍스트 메시지 끝*/
/*그림 메시지에 회답, 최대 6개(위챗은 10개 지원)*/
msgType = “news”; String contentHtml = ";//사용자 요청 키워드
if(keyword.equals(“help”) || keyword.equals(도움말)|||keyword.equals("?") | | keyword.equals("?") {//사용 설명서
  //String helpHtml  =  "
, \"help\" \" \" 。
(c: ,c: ,c: )
([2013-10-05]: ,[d:9]: 9 ,[d:-9]: 9 , 10 )"; String helpPicUrl = "http://www.daniu.co/images/weixin/help_640_320.png"; String helpContentUrl = ""; String helpResults = "<item><Title><![CDATA[ ]]></Title><Description><![CDATA[" + helpHtml + "]]></Description><PicUrl><![CDATA[" + helpPicUrl +"]]></PicUrl><Url><![CDATA["+ helpContentUrl +"]]></Url></item>"; helpResults = "<ArticleCount>1</ArticleCount><Articles>"+ helpResults; String resultStr = htmlTpl.format(htmlTpl, fromUsername, toUsername, time, msgType, helpResults); this.print(resultStr);

}else {//스마트 응답
  String reqTpl = "<xml><ToUserName><![CDATA[%1$s]]></ToUserName><FromUserName><![CDATA[%2$s]]></FromUserName><CreateTime>%3$s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + keyword + "]]></Content><MsgId>5937584354468300645</MsgId><OpenId>daniuco</OpenId></xml>";
  String reqStr = reqTpl.format(reqTpl,toUsername, fromUsername, time);//              ,  toUsername,fromUsername  

  contentHtml = getRemoteXML(reqStr);
 // System.out.print(contentHtml);
  //          
  this.print(contentHtml);

}
//정보를 위챗 서버로 되돌려줍니다//this.print(resultStr); }else{ this.print(“Input something…“); } }else { this.print(““); } }
//위챗 인터페이스 검증 public boolean checkSignature() {String signature = final request.getParameter("signature"), String timestamp = final request.getParameter("nonce), String token=TOKEN, String [] tmpAr={token, timestamp, nonce}, StringArrays.sort(tmpArr); String tmpStr=this.ArrayToString(tmpArr); tmpStr=this.SHA1Encode(tmpStr); if(tmpStr.equalsIgnoreCase(signature)){ return true; }else{ return false; } }
//요청자에게 반환 데이터public void print(String content) {try {final response.getWriter().print(content);final response.getWriter().flush();final response.getWriter().close();catch(Exception e) {}//배열 전환 문자열public String Array Tostring(String [] arr) {StringBuffer bf = new StringBuffer(), for(int i = 0; i //sha1 암호화 public String SHA1 Encode(String sourceString) {String resultString = null;try {resultString = new String(source String), Message Digest md = Message Digest.gest.get Instance("SHA-1"), result String = byte2 hex String(md.digest(resulting.gestring.get Bytes),catch (Exception ex) { } return resultString; } public final String byte2hexString(byte[] bytes) { StringBuffer buf = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { if (((int) bytes[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString((int) bytes[i] & 0xff, 16)); } return buf.toString().toUpperCase(); }//입력 흐름에서post 매개 변수 읽기
public String readStreamParameter(ServletInputStream in){ StringBuilder buffer = new StringBuilder(); BufferedReader reader=null; try{ reader = new BufferedReader(new InputStreamReader(in)); String line=null; while((line = reader.readLine())!=null){ buffer.append(line); } }catch(Exception e){ e.printStackTrace(); }finally{ if(null!=reader){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return buffer.toString(); }
}%>
<%! public String getRemoteXML(String reqStr) {
 HttpURLConnection url_con = null;
 String responseContent = null;

 String daniucoUrl = "http://www.daniu.co/openapi";
 try
    {

        URL url = new URL(daniucoUrl);
        url_con = (HttpURLConnection) url.openConnection();
        url_con.setRequestMethod("POST");
        url_con.setDoOutput(true);
        byte[] b = reqStr.getBytes();
        url_con.getOutputStream().write(b, 0, b.length);
        url_con.getOutputStream().flush();
        url_con.getOutputStream().close();

        InputStream in = url_con.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                "utf-8"));
        String tempLine = rd.readLine();
        StringBuffer tempStr = new StringBuffer();
        String crlf=System.getProperty("line.separator");
        while (tempLine != null)
        {
            tempStr.append(tempLine);
            tempStr.append(crlf);
            tempLine = rd.readLine();
        }
        responseContent = tempStr.toString();
        rd.close();
        in.close();
    }
    catch (IOException e)
    {
        //System.out.print("    ", e);
    }
    finally
    {
        if (url_con != null)
        {
            url_con.disconnect();
        }
    }
    //System.out.println(responseContent);
    return responseContent;

}
%>
<% WeiXinHandler t=new WeiXinHandler(); t.valid(); %>

좋은 웹페이지 즐겨찾기