[Funded in Yesky]
Summary
In the last part of this MIDP series, I will introduce the communication method 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.
Connection level
All interfaces in the 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, and it also provides some other ways to perform HTTP interactions. Here are some of these useful methods:
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.
CONNECTOR object
How do the MIDP API know which interface wants to create and returns to the called class? 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 to find a 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??????????????? The connection string Http??????????????? Http://www.yahoo.com Stream-based Socket?? ???????? DataGram: //: 6160? DataGram-based socket - sending?? DataGram: //121.232.121.232: 6160? Serial port??? ????????? comm: 0; baudrate = 5000 File file:.???????????????? //helloWorld.txt examples
The following examples combine the things discussed herein together. 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. When downloaded, it creates an instance of the voteereSults object:
Public class votermidlet Extends MIDlet imports screencallback {; private display _display; // midlet Has Three Screens Private voteerates votesults = new voteResults (ScreenCallback);
Public votermidlet () {; _display = display.getdisplay (this); _display.setcurrent (voteerates);
Public void exit () {; try {; this.destroyApp (true);}; catch (MIDletStateChangeexception E) {;};
ScreenCallback
As shown above, the votermidlet implements 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.
Voteerates
VoteResults is a user interface class that shows the results of the voting to the user. 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. Here is some of interest:
Votesummary votesummary = Resourceility.getvotesummary (); Initialize; • The above code is responsible for initializing the communication of the MIDlet and JSP pages, which simulates 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 all possible votes and corresponding votes:
public void initialize (VoteSummary voteSummary) {; append (getNumVotesString (voteSummary.getNumVotes ())); append (getAvgVoteString (voteSummary.getAvgVote ())); append (showVoteResults (voteSummary.getVotes ()));};
When the user is input, the command () method is called. 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 successd iteminary {; Vote newvote = new vote ("" SELECTEDINDEX, NULL, NULL);
Votesummary votesummary = resourceutility.adden (newvote);
Update (votesummary);};}; votesummary
The votesummary object contains status information with current voting. It tracks all voting numbers, average votes, and a VECTOR that maintains voting (voting information for each option):
Public votesummary (string numvotes, string avgvote, vector votes) {; _ numvotes = numvotes; _votes = votes;
The VotesumMary object is created based on the XML returned by JSP to the MIDlet.
ResourceUtility
The ResourceUtility class gets XML information on the remote server. It uses HTTPConnection by the JSP to get XML, and then convert these XML into a votesummary object via XMLUTIL:
Public static votesummary getvotesummary () {; string xml = loadingvotereSults (); return converTxmltovotesummary (XML);
The above GetVotesummary () method accesses 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 voting for background systems:
public static String loadVoteResults () {; return backendComms (LOAD_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.openputStream ());
INT INPUTCHAR;
// check the content-length = httpConnection.getLength ();
IF (ContentLength! = - 1) {; for (INT i = 0; I {; IF (IF (INPUTCHAR = DataInputStream.Read ())! = -1) {; MessageBuffer.Append ((char) infutchar); };}; Else {; // if the content-length is not available while ((InputChar = DataInputStream.read ())! = -1) {; MessageBuffer.Append ((char) infutchar);}; .Close ();
}; cardch (IOEXCEPTION IOE) {; MessageBuffer = New StringBuffer ("ERROR!");}; catch (Exception E) {; E.PrintStackTrace ();}; finally {; try {; if (httpConnection! = null) {httpConnection.close ();}; catch (IOException ignored) {;}; try {; if (dataInputStream = null!) dataInputStream.close ();}; catch (IOException ignored) {;};}; return messagebuffer. Tostring ();}; The following we 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.openputStream ());
To get an HTTPConnection implementation, we call the 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 JSP to get the result of the result inputStream:
IF (ContentLength! = - 1) {; for (INT i = 0; I {; IF (IF (INPUTCHAR = DataInputStream.Read ())! = -1) {; MessageBuffer.Append ((char) infutchar); };}; else {; // if the content-length is not available while ((InputChar = DataInputStream.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 you get an EOF or an error. Each character read by DataInputStream is added to the StringBuffer. This StringBuffer contains a voting result of an XML representation, which will be transferred to the method, then transferred to the Convertxmltovotesummary () method, as shown below:
private static VoteSummary convertXMLToVoteSummary (String xml) {; InputStreamReader insr = new InputStreamReader (new ByteArrayInputStream (xml.getBytes ())); VoteSummary voteSummary = null;
Try {; votesummary = xmlutil.getvotereSults (InSR);
}; caratch (ioexception ie) {;};
Return votesummary;
This method converts the XML string into a Java object so that we can use the method to get the data instead of analyzing data. We use the XMLUTIL.GetVoteResults () method to do this. Before contacting the method, let's complete the ResourceUtility object first. The final method is addentry (), transferring new votes to JSP. As mentioned above, for efficiency, it uses a backendcomms () method again:
Public static votesummary addentry (vote vote) {; stringbuffer requeststring = new stringbuffer ();
RequestString.Append (Question vote.torequestString ());
String XML = Backendcomms (loading_url, requeststring.toString ());
Return Convertxmltovotesummary (XML);}; XMLUTIL
The XMLUTIL 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.
Here is the getVoteResults () method in this object, let's take a look at how the conversion process is:
Public static votesummary getvotereSults (InputStreamReader Insr) throws ioException {; XmlParser Parser = New XMLPARSER (InSR);
Document 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 objects. 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 verifying information, you can call Ocument.write to remove the previous comments, to see the structure of the document:
Element voteExampleElement = document.getElement ( "vote-example"); Element voteElement = voteExampleElement.getElement ( "votes"); String numVotes = getTextFromElement (voteElement, "number"); String avgVote = getTextFromElement (voteElement, "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 text nodes from the document and return it:
Element choicesElement = votelement.getlement ("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 Choicevalue = getTextFromElement (ChoiceElement, "Value"); Choicename = getTextFromElement (choiceElement, "name"); choicevotes = getTextFromElement (ChoiceEleMent, "Number"); vote = new vote (choicevalue, choicename, choicevotes); VENTRIES.AddeElement (vote); Return New Votesummary (Numvotes, Avgvote, Ventries); This allows us to get the number of child elements, and then you can traverse them and get the vote information. Some of the child nodes are Element, while others are a TEXT node without data. In this example, we only care about Elements, so we have to set the appropriate conditions in the loop. This loop will get each sub-Elements by the option element, and construct a Vote object, which contains the number of values (used as calculations), names, and votes. These Vote objects are sequentially added to the Vector. Finally, this method initializes a new VotesumMary object that contains three information above. Private static string getTextFromElement (Element ElementName) {; string returnText = elementroot.get (ElementName) .getText (); Return ReturnText;}; We use the getTextFromelement () method to make the code more readable. Its role is to go deep into the tree structure, and get the Text node information therein. voter.jsp The last element of this system is JSP of analog backend system. In this example, I created a simple JSP that uses class variables to track voting calculations. Specific JSP see source code. It is just tracked votes and returns data represented by XML. Last point This example explains the MIDP and a server-side component if interacting via HTTPConnection. By issuing a request, the MIDP can communicate with the JSP component via a normal HTTP GET / POST call. In this example, the call returns to XML information. With the KXML analyzer, XML can be effectively converted to an object, and the graphics class can be obtained from the object. You also have to note that there is no need to define the number of options in the choicegroup in the application, but is dynamically set by the server side. Like any multi-storey development task, we must consider how to effectively implement the Model-View-Controller model and avoid creating extra code. This idea is also reflected in this example. This model is JSP. View is a votereSults object that displays all data information. The Controller here is also a voteresults object because it implements the CommandListener interface. Communicate In this article, we mainly discussed a MIDP communication system that produces HTTP requests. These requests can be a privilege protocol that uses a standard protocol to any application level protocol using a private protocol. The APIs can be flexibly handled in a very similar way. When you interact with the remote machine, if you are in a region that covers (for example, when you enter a tunnel), what will happen? Unlike WAP, when it is in an area covered, the phone with MIDP function can continue to run its application. This technology can make users use offline functions and have the ability to synchronize online with online application when returning to the overlay area. For example, a MIDP-based Email application: Users can continue to read and respond to email that has been downloaded to local RMS Datastore. When returning to the overlay area, the recovered information can be sent to the server to distribute to different recipients. The currently released J2ME Wireless Toolkit version does not support HTTPS protocols. However, the earlier released developer version does support HTTPS. With these API support, you can implement trading stocks on the Java phone or for sale. About this series of articles This series of articles is to introduce the readers to the J2ME MIDP. As with other Java implementations, its API will take some time to mature. Here is just a summary of the summary of the main class and the prospect of MIDP. Many ways also need to study by readers. The first part introduces the reader's introduction to J2MEWTK, discusses the basic point of the MIDP configuration file, and the graphic application is also introduced. The second part, through a text-based example, I discussed the local storage capacity of MIDP in detail. Data storage capability is an important part of the MIDP API because it allows you to use offline features in the MIDP protocol. The third part discusses the ability of MIDP access to remote servers. If a device cannot access the external network data, then its role is also limited, so these APIs are very important for development. Through this series, you will be able to create a MIDP app very easy. After a period of time, equipment with Java features will be more popular, and cross-platform interactions will also be more standardized. When these become a reality, it is also the time when J2ME is too much.