Abstract In the last part of this MIDP series, I will introduce the communication methods between MIDlet and external systems. Developers can interact with external systems using the API included in the MIDP of Java2 Micro Edition. This article will introduce these APIs in a detailed example, which demonstrates the J2ME device and a SERVLET-based Web system. In the previous two parts, the features and functions of the MIDP API I introduce are related to the operation and information storage of the device itself. In this last part, I will focus on the interaction between network devices and large networks. Network devices can use few unclear protocols to communicate with each other. In this article, I will focus on the HTTPConnection interface, you can access information stored on a web server through it. Before introducing the examples of this article, I will discuss the interaction of javax.microedition.io interfaces and classes, and examples are set in the MIDP device and a JSP system-based interaction. All interfaces in the connection hierarchy javax.microEdition.IO package are based on the Connection interface. Other connection interfaces inherit the method in the connection, and define a method for accessing the associated variable and the CONNECTION type action. I will talk about the most common interface in this article, and other interfaces are left to readers. HTTPConnection Description The HTTPConnection interface is built on the Connection interface, which provides some other ways to perform HTTP interactions. Here are some useful methods list: String getHeaderField (int index) String getHeaderField (String name) long getHeaderFieldDate (String name, long def) int getHeaderFieldInt (String name, int def) String getHeaderFieldKey (int n) String getHost () long getLastModified () int getPort () String getProtocol () String getQuery () String getRef () String getRequestMethod () String getRequestProperty (String key) int getResponseCode () String getResponseMessage () String getURL () void setRequestMethod (String method) void setRequestProperty ( String Key, String Value These methods allow you to access the HTTP field as a servlet-based system. Other interfaces have a clear definition in the API specification document. These interfaces have some methods that can use different protocols to send and receive packets or stream data. Here I will not discuss this in more detail because it is the same in the form. How does the Connector object MIDP API know which interface wants to create and returns to the class to call? The answer is that the returned Connector is based on the value transmitted to the connection string. The following connection strings are to remind the Connector object system is looking for an httpConnection: httpconnection httpconn = connector.open ("
http://www.itpath.com ");
The MIDP Connector object analyzes the connection string, know this is a URL used as access to the webpage, which will return an implementation of an HTTPConnection interface to the class. Other connection protocols require different connection strings. The following table is a list of them: protocol connection string HTTP
http: //www.yahoo.comStream-based Socket Socket: // localhost: 6160 Datagram-based Socket - listening datagram: //: 6160 Datagram-based Socket - sending datagram: //121.232.121.232: 6160 Serial Port comm. : 0; Baudrate = 5000 file file: //HelloWorld.txt example The following examples will be combined with the things discussed in this article. In this example, the MIDlet access is information stored on a remote system. This information is returned to the MIDlet in the form of an XML. By analyzing the XML, the MIDlet constructs a user interface based on this data. The user interface consists of a problem. After the user is submitted, the request will be requested to add the data. Then return to the updated data to the user. Through this detailed example, you can learn more about the basic usage and syntax of the J2ME Connection API. Votermidlet votermidlet is the only MIDlet in this example. Upon downloading, it creates an instance of an object VoteResults: public class VoterMidlet extends MIDlet implements ScreenCallback {; private Display _display; // midlet has three screens private VoteResults voteResults = new VoteResults ((ScreenCallback) this); public VoterMidlet () {; _display = display.getdisplay (this); _display.setcurrent (votereSults);}; public void exit () {; try {; this.destroyApp (true);}; catch (MIDletStateChangeException E) {;};}; .. ScreenCallback As shown above, the votermidlet implemented the ScreenCallback interface. This interface hides the UI class and some events, otherwise the UI class may require a reference to the MIDlet. The ScreenCallback interface contains a single method public void exit (), the UI screen uses this method to remind the MIDlet, the user has pressed the "EXIT" button. By writing code for ScreenCallback, other MIDlet methods are independent of developers of the UI screen. This is very important, because if not improper use, some MIDlet methods will bring destructive consequences. VotereSults VotereSults is a user interface class that displays the result of voting to users. To make the example simplified, the interface implements two model-view-controller classes: View and Controller. This constructor receives a unique parameter -screencallback interface in the MIDLET. As mentioned above, the interface allows SCREEN to be able to call some methods of the MIDlet. The constructor initializes the object and creates an example of the user interface. The following is some of which are interested in: votesummary votesummary = resourceility.getvotesummary (); Initialize (votesummary); The above code is responsible for initializing the MIDlet and JSP pages, it Simulated is a real system.
Resourceility Access a URL via HTTP parameters and get information from this JSP. It uses this information to create a votesummary object. In the following examples we will further discuss this interface. Then, the initialize () method will then create a UI display, which includes two stringItems to display the previous voting results, and a choiceGroup contains possible voting and corresponding votes: public void initialize (votesummary votesummary) {; Append (Votesummary.GetNumvotes)); append (votesummary.getavgvote ())); append (showvotereSults ());}; . This method receives the input of the device. If the input command is "vote", the current option is obtained by choicegroup. At this time, a Vote object is constructed and transmitted to the resource depient.addenTry () method. This method will transmit information to JSP, JSP will add new votes to the record and return an updated votesummary object. Then it will call the update () method: public void command (Command C, Displayable S) {; string command = c.getlabel (); if (Command.Equals ("exit")) {; _Screencallback.exit (); }; else if (command.equals ( "Vote")) {; // get the selected item int selectedIndex = _voteResults.getSelectedIndex (); Vote newVote = new Vote ( "" selectedIndex, null, null); voteSummary voteSummary = ResourceIlity.AddenTry (newvote); Update (votesummary);};}; votesummary votesummary object contains status information with current voting. It tracks all votes, average voting, and a VECTOR that maintains voting (Vote for each option): public votesummary (String Numvotes, string avgvote, vector votes) {; _ number = numvotes; _avgvote = avgvote; _votes = votes;}; If the XML returns from JSP to MIDlet, a VotesumMary object will be created. The ResourceIlity ResourceUtility class gets XML information on the remote server. It is obtained by the use HttpConnection the JSP XML, and will pass these XMLUtil VoteSummary XML into a subject: public static VoteSummary getVoteSummary () {; String xml = loadVoteResults (); return convertXMLToVoteSummary (xml);}; above getVoteSummary ( Method Access this object.
This method will call the LoadvoteResults () and Convertxmltovotesummary () methods sequentially.
The loadvoteresults () method is as follows, which calls the backendcomms () method, which is used to increase vote for the background system: public static string loadvoteResults () {; return backendcomms (loading_url, ");}; private static string backendcomms String requestURL, String requeststring) {; HttpConnection httpConnection = null; DataInputStream dataInputStream = null; StringBuffer messagebuffer = new StringBuffer (); String requestString = requestURL requeststring; Try {; // Open an HTTP connection with the Web server httpConnection = (HttpConnection ) Connector.open (requestString, Connector.READ_WRITE); // Set the request method to GET httpConnection.setRequestMethod (HttpConnection.GET); // Retrieve the response back from the servlet dataInputStream = new DataInputStream (httpConnection.openInputStream ()); INT INPUTCHAR; // Check the content-length = httpConnection.getLength (); if (ContentLength! = - 1) {; for (INT i = 0; i {; IF ((Inputchar = DataInputStream.read () )! = -1) {; MessageBuffer.Append ((char) inputchar); };};}; Else {; // if the content-length is not available while ((InputChar = DataInputStream.read ())! = -1) {; messageBuffer.Append ((char) infutchar);}; DataINputStream.close ();}; catch (ooException ooe) {; messagebuffer = new stringbuffer ("error!");}; Catch (exception e) {; E.PrintStackTrace ();}; finally {; if (! httpConnection = null) {httpConnection.close ();}; catch (IOException ignored) {;}; try {; if (dataInputStream = null!) dataInputStream.close ();}; catch (IOException ignored) {; (};);
Let's discuss the Backendcomms () method. First start with the try-catch block. The first step is to open a read / write httpConnection to the server. I have already said above, this method gets XML and write a request for the server, so we need to use a READ_WRITE connection: try {; // open an http connection with the web server httpconnection = (httpConnection) Connector.Open (RequestString, Connector .READ_WRITE); // Set the request method to gET httpConnection.setRequestMethod (HttpConnection.GET); // Retrieve the response back from the JSP dataInputStream = new DataInputStream (httpConnection.openInputStream ()); to get a HttpConnection achieved, we call Connector.open () method. This class contains a static method that generates a corresponding interface for communication based on the connection string. In this example, we have to get an HTTPConnection, so we put the response of the connector.open () into the HTTPConnection interface. Once we issued a request, we can use the openinputstream () method of the HTTPConnection object, which can be obtained from the result of the result in the JSP (ContentLength! = - 1) {; for (int i = 0; I {; IF) INPUTCHAR = DATAINPUTSTREAM.READ ())! = -1) {; MessageBuffer.Append ((char) infutchar);};};}; else {; // if the content-length is not available while .read ())! = -1) {; messageBuffer.Append ((char) infutchar);};}; then you can read the length of the response content, if you don't find it, you can also read it until get it An EOF or a wrong character. Each character read by DataInputStream is added to StringBuffer. This StringBuffer contains a voting result of XML represented, which will be transferred to CONVERTXMLTOVOTESUMMARY. ) method as follows: private static voteSummary convertXMLToVoteSummary (String xml) {; InputStreamReader insr = new InputStreamReader (new ByteArrayInputStream (xml.getBytes ())); voteSummary voteSummary = null; Try {; voteSummary = XMLUtil.getVoteResults (insr) ;}; OoException ie) {;}; returnvotesummary;}; This method converts the XML string into a Java object so that we can use the method to get the data instead of analysis data. We use XMLUTIL.GetVoteResults ( The method is to do this conversion.
Before contacting the method, let's complete the ResourceUtility object first. The final method is addentry (), transferring new votes to JSP. As described above, for efficiency, it is used again backendComms () method: public static VoteSummary addEntry (Vote vote) {; StringBuffer requestString = new StringBuffer (); requestString.append (QUESTION vote.toRequestString ()); String xml = backendComms (Load_url, RequestString.toString ()); Return ConvertXMLTOVOTESUMMARY (XML);}; XMLUTIL XMLUTIL object The role of the object is to convert XML received by JSP to a votesummary object for use. To complete the conversion, it must use an XML analyzer to resolve data. In order to reduce the overall size of the MIDlet, use a lightweight analyzer to minimize the overall size of the MIDlet. In this example, I am using Enhydra's KXML analyzer. The following is getVoteResults this object () method, we look at how the conversion process is carried out: public static VoteSummary getVoteResults (InputStreamReader insr) throws IOException {; XmlParser parser = new XmlParser (insr); Document document = new Document () Document.Parse (Parser); File: // UNcomment to see the document Written to Your Console. File: //document.write (New OutputStreamWriter (SYSTEM.out)); the first few lines are setting XMLParser and Document object. After creating these objects, the Document.Parse () method is called, and XMLParser is transmitted as a parameter. The result of the document contains XML information transmitted by JSP. If you are interested in the format of the verification information, you can call the Ocument.write to remove the comment to see the structure of the document: element voteexampleElelement = document.getlement ("vote-example"); element voteElement = voteexampleElement.getlement ( "votes"); string numvotes = getTextFromElement (votelement, "number"); string avgvote = getTextFromElement (votelement, "average"); After creating Document, we can now get the Element object and get the value. The first two lines are used to move in the XML document to reach nodes containing data.
After getting the votelement node, we can use the getTextFromelement () method, this method performs multiple commands to get the text node from the document, and returns its value: element choiceselement = votelement.getElement ("choices"); int Childcount = choicesElement .getchildcount (); The above two lines of code are used to acquire the number of nodes under the selection area. With ChildCount, you can construct nodes so that you don't need to use the current voting. This is important because you may need to join more votes later. Use these calls, you can do this without modifying the code: for (int i = 0; i