I feel that development is the interface to be called, so when there is no schedule for work, I will check and try to call the interface. to call the interface, I need to send http get and post requests, so I 'd better write an httputil class first, I specially send get and post requests. However, my java Network programming skills are not good, so some Baidu code is encapsulated by myself and can be used normally, the code is as follows. let's take a look at the developed Message Interface.
I feel that development is the interface to be called, so when there is no schedule for work, I will check and try to call the interface. to call the interface, I need to send http get and post requests, so I 'd better write an httputil class first, I specially send get and post requests. However, my java Network programming skills are not good, so some Baidu code is encapsulated and can be used normally. the code is as follows:
Import java. io. bufferedReader; import java. io. dataInputStream; import java. io. dataOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. printWriter; import java.net. httpURLConnection; import java.net. URL; import java.net. URLConnection; import java. util. iterator; impor T java. util. map; import javax. activation. mimetypesFileTypeMap;/***** @ author luolei **/public class HttpUtil {public static String httpGet (String httpUrl) {StringBuffer buffer = null; try {URL url = new URL (httpUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url. openConnection (); httpUrlConn. setDoInput (true); httpUrlConn. setRequestMethod ("GET"); // gets the input stream InputStream inputStream = httpU RlConn. getInputStream (); InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); // read the returned result buffer = new StringBuffer (); string str = null; while (str = bufferedReader. readLine ())! = Null) {buffer. append (str);} // releases the resource bufferedReader. close (); inputStreamReader. close (); inputStream. close (); httpUrlConn. disconnect ();} catch (Exception e) {e. printStackTrace ();} return buffer. toString ();}/*** send post request, */public static String httpPost (String httpUrl, String data) {PrintWriter out = null; BufferedReader in = null; string result = ""; try {URL realUrl = new URL (httpUrl );// Enable the URL connection URLConnection conn = realUrl. openConnection (); // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // the following two rows of conn must be set to send a POST request. setDoOutput (true); conn. setDoInput (true); // get the output stream of the URLConnection object out = new PrintWriter (conn. getOutputStrea M (); // sends the request parameter out. print (data); // flush the buffer out of the output stream. flush (); // defines the BufferedReader input stream to read the URL response in = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line; while (line = in. readLine ())! = Null) {result + = line;} catch (Exception e) {System. out. println ("An Exception occurred when sending the POST request! "+ E); e. printStackTrace () ;}// use finally blocks to close the output stream and input stream finally {try {if (out! = Null) {out. close () ;}if (in! = Null) {in. close () ;}} catch (IOException ex) {ex. printStackTrace () ;}} return result ;} /*** upload an image ** @ param urlStr * @ param textMap * @ param fileMap * @ return */public static String formUpload (String urlStr, Map
TextMap, Map
FileMap) {String res = ""; HttpURLConnection conn = null; String BOUNDARY = "--------------------------- 123821742118716 "; // boundary is the separator between the request header and the content of the uploaded file. try {URL url = new URL (urlStr); conn = (HttpURLConnection) url. openConnection (); // System. out. println (conn); conn. setConnectTimeout (5000); conn. setreadtimeouts (30000); conn. setDoOutput (true); conn. setDoInput (true); conn. setUseCaches (false); conn. SetRequestMethod ("POST"); conn. setRequestProperty ("Connection", "Keep-Alive"); conn. setRequestProperty ("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv: 1.9.2.6)"); conn. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + BOUNDARY); OutputStream out = new DataOutputStream (conn. getOutputStream (); // text if (textMap! = Null) {StringBuffer strBuf = new StringBuffer (); Iterator iter = textMap. entrySet (). iterator (); while (iter. hasNext () {Map. entry entry = (Map. entry) iter. next (); String inputName = (String) entry. getKey (); String inputValue = (String) entry. getValue (); if (inputValue = null) {continue;} strBuf. append ("\ r \ n "). append ("--"). append (BOUNDARY ). append ("\ r \ n"); strBuf. append ("Content-Disposition: Form-data; name = \ "" + inputName + "\" \ r \ n "); strBuf. append (inputValue);} out. write (strBuf. toString (). getBytes ();} // file if (fileMap! = Null) {Iterator iter = fileMap. entrySet (). iterator (); while (iter. hasNext () {Map. entry entry = (Map. entry) iter. next (); String inputName = (String) entry. getKey (); String inputValue = (String) entry. getValue (); if (inputValue = null) {continue;} File file = new File (inputValue); String filename = file. getName (); String contentType = new MimetypesFileTypeMap (). getContentType (file); if (file Name. endsWith (". png ") {contentType =" image/png ";} if (contentType = null | contentType. equals ("") {contentType = "application/octet-stream";} StringBuffer strBuf = new StringBuffer (); strBuf. append ("\ r \ n "). append ("--"). append (BOUNDARY ). append ("\ r \ n"); strBuf. append ("Content-Disposition: form-data; name = \" "+ inputName + "\"; filename = \ "" + filename + "\" \ r \ n "); strBuf. append ("Content-Typ E: "+ contentType +" \ r \ n "); out. write (strBuf. toString (). getBytes (); 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 [] endData = ("\ r \ n --" + BOUNDARY + "-- \ r \ n "). getBytes (); out. write (endData); out. flush (); out. close (); // read the returned data StringBuffer strBuf = new StringBuffer (); BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream (); String line = null; while (line = reader. readLine ())! = Null) {strBuf. append (line ). append ("\ n");} res = strBuf. toString (); reader. close (); reader = null;} catch (Exception e) {System. out. println ("An error occurred while sending the POST request. "+ UrlStr); e. printStackTrace ();} finally {if (conn! = Null) {conn. disconnect (); conn = null ;}} return res ;}}
HttpGet and httpPost are used to send get and post requests. in the development process, message interfaces are generally in xml format. other interfaces generally upload and return data in json format, therefore, a json parsing package is required. I use fastjson, and gson can also be used.
To test the Message Interface, first understand the request process:
The server sends a get request based on the entered url for verification. when the verification succeeds, the server sends a post request based on the url. the Message format is xml.
Message Type development documents include text, images, voice, and other messages, as well as events such as follow, click, and jump.
These messages and events are in xml format. therefore, to parse messages in xml format, I use dom4j for parsing,
Parse the message by verifying the Accessed servlet's doPost method,
I wrote a MessageUtil according to the method written in Liu Feng's blog, which encapsulates the xml Parsing method and places the parsed result in map. The specific code is as follows:
Public static Map
ParseXml (HttpServletRequest request) throws Exception {// store the parsing result in the HashMap Map
Map = new HashMap
(); // Obtain the InputStream inputStream = request from the request. getInputStream (); // read the input stream SAXReader reader = new SAXReader (); Document document Document = reader. read (inputStream); // Get the xml root Element root = document. getRootElement (); // obtain the List of all child nodes of the root element.
ElementList = root. elements (); // traverse all subnodes for (Element e: elementList) map. put (e. getName (), e. getText (); // release the resource inputStream. close (); inputStream = null; return map ;}
The parsed xml is saved in the map according to the tag name-content.
Then you can retrieve the message type msgType.
String msgType = requestMap. get ("MsgType ");
Then determine the message type and different message types for different servlets to process,
// Text message if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_TEXT) {request. getRequestDispatcher ("TextMessage "). forward (request, response);} // Image message else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_IMAGE) {request. getRequestDispatcher ("ImageServlet "). forward (request, response);} // else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_LOCATION) {request. getRequestDispatcher ("LocationServlet "). forward (request, response);} // The else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_LINK) {request. getRequestDispatcher ("LinkServlet "). forward (request, response);} // The audio message else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_VOICE) {request. getRequestDispatcher ("VedioServlet "). forward (request, response);} // event push else if (msgType. equals (MessageUtil. REQ_MESSAGE_TYPE_EVENT) {// event type String eventType = requestMap. get ("Event"); // subscribe to if (eventType. equals (MessageUtil. EVENT_TYPE_SUBSCRIBE) {request. getRequestDispatcher ("SubServlet "). forward (request, response);} // unsubscribe to else if (eventType. equals (MessageUtil. EVENT_TYPE_UNSUBSCRIBE) {// after TODO cancels the subscription, the user cannot receive the message sent by the public account, so no reply message is required} // Click the event else if (eventType. equals (MessageUtil. EVENT_TYPE_CLICK) {// The TODO custom menu permission is not open and the request for this type of message is not processed. getRequestDispatcher ("ClickServlet "). forward (request, response );}}
Different servlets process different messages. different messages can be returned as needed. the format of returned messages is also in xml format. The Returned message type is similar to the accepted message type, the returned messages can be encapsulated. Each xml tag corresponds to the field name and the content is the field content.
Example:
Public class BaseMessageResp {// recipient account (received OpenID) private String ToUserName; // developer id private String FromUserName; // message creation time (integer) private long CreateTime; // message type (text/music/news) private String MsgType; // The private int FuncFlag message received by Star when 0x0001 is marked;
The set and get methods are omitted.
Public class TextMessage extends BaseMessageResp {// reply message Content private String Content; public String getContent () {return content;} public void setContent (String Content) {content = Content ;}}
Because different messages have the same fields, a general base class is written.
It is still one step away from returning a message to the user. the technology converts these pojo classes into xml strings.
Xstream is used.
/*** Convert a text message object to xml *** @ param textMessage the text message object * @ return xml */public static String textMessageToXml (TextMessage textMessage) {xstream. alias ("xml", textMessage. getClass (); return xstream. toXML (textMessage );}
Here is just a simple description. for details, refer to Liu Feng's blog. I forgot the link. I should be able to go to Baidu's
Finally, return the string to the server to reply to the user.
You can use only these message interfaces to write a simple subscription number. Normally, the company's public number seems to jump to its own website through the view button.
Now we can use the above interface to accept various messages sent by users, and then send messages in advance. you can handle the messages by yourself, or call APIs such as weather, jokes, articles, and so on to get the results, after the resolution, return the result to the user in the desired format. you can practice a subscription number such as a life assistant. However, the subscription number applied by an individual has limited permissions and I don't know if it is competent.
The above is the details of the developed Message Interface. For more information, see other related articles on php Chinese network!