Comprehensive Analysis of MIDP communication API and external system interaction

Source: Internet
Author: User
Summary

In the last part of this MIDP series, I will introduce the communication methods between the MIDlet and external systems. Using the APIS contained in MIDP of Java2 Micro Edition, developers can interact with external systems. This article will describe these Apis with a detailed example. It demonstrates the interactions that can be performed between a j2-based device and a servlet-based web system.

In the previous two parts, the features and functions of the midp api I introduced are related to the operation of the device and information storage. In the last section, I will focus on the interaction between network devices and large networks.

Network devices can communicate with each other using countless protocols. In this article, I will focus on the httpconnection interface, through which you can access the information stored on a Web server. Before introducing the example in this article, I will discuss the interaction between javax. microedition. Io interfaces and classes. The example focuses on the interaction between a MIDP device and a JSP-based system.

Connection level

All interfaces in the javax. microedition. Io package are based on the connection interface. Other connection interfaces inherit the methods in connection and define methods used to access related variables and the action of this connection type. I will talk about the most common interfaces in this article, and leave other interfaces for readers to study.

Httpconnection description

The httpconnection interface is created on the connection interface. It also provides some other methods for HTTP interaction. The following lists some 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 HTTP fields like servlet-based systems.

Other interfaces are clearly defined in the API specification document. These interfaces come with methods that can use different protocols and devices to send and receive data packets or stream data. I will not discuss this in detail here, because the form is the same.

Connector object

How does the midp api know which interface to create and return to the called class? The answer is that the returned connector is based on the value sent to the connection string.

The following connection string indicates that the connector Object System is searching for an httpconnection:

Httpconnection httpconn = connector. Open ("Http://www.itpath.com ");

The MIDP connector Object Analyzes the connection string and knows that this is a URL used to access the webpage. Therefore, an httpconnection interface implementation is returned to the called class.

Other connection protocols require different connection strings. The following table lists them:

Protocol connection string
HTTPHttp://www.yahoo.com
Stream-based Socket socket: // localhost: 6160
Datain-based socket-listening datasync: //: 6160
Datasync-based socket-sending datasync: // 121.232.121.20.: 6160
Serial Port comm.: 0; baudrate = 5000
File file: // helloworld.txt

Example

The following examples combine the things discussed in this article. In this example, the MIDlet accesses the information stored on a remote system. This information is returned to the MIDlet in XML format. By analyzing the XML, the MIDlet constructs a user interface based on the data.

The user interface consists of a problem. After the user submits the request, the server will be requested to add the data. Then, the updated data is returned to the user.

Through this detailed example, you can have a better understanding of the basic usage and syntax of the j2_connection API.

Votermidlet

Votermidlet is the only MIDlet in this example. During download, it creates an instance of the voteresults object:

Public class votermidlet extends MIDlet implements screencallback
{;
Private display _ display;
// MIDlet has three screens
Private 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, votermidlet implements the screencallback interface. This interface hides the UI class and some events. Otherwise, the UI class may need a reference to the MIDlet. The screencallback Interface contains a single public void exit () method. The UI screen uses this method to remind the MIDlet that the user has pressed the "exit" button.

By writing code for screencallback, other MIDlet methods are irrelevant to the developer of the UI screen. This is important because some MIDlet methods will cause destructive consequences to the program if improperly used.

Voteresults

Voteresults is a user interface class used to display the voting result to the user. To simplify the example, this interface implements two Model-View-controller classes: View and controller.

The constructor receives the unique parameter "screencallback" interface from the MIDlet. As mentioned above, this interface enables screen to call back some methods of the MIDlet.

The User Interface on which the constructor initializes the object and creates an example. The following are interesting parts:

Votesummary = resourceutility. getvotesummary ();
Initialize (votesummary );

The above code initializes the communication between the MIDlet and JSP pages. It simulates a real system. Resourceutility accesses a URL through the HTTP parameter and obtains information from the JSP. It uses this information to create a votesummary object. In the following example, we will further discuss this interface.

Then the initialize () method is called to create the UI display. Two stringitems display the preceding voting results, and one choicegroup contains all possible voting values and corresponding voting values:

Public void initialize (votesummary)
{;
Append (getnumvotesstring (votesummary. getnumvotes ()));
Append (getavgvotestring (votesummary. getavgvote ()));
Append (showvoteresults (votesummary. getvotes ()));
};

The commandaction () method is called when the user inputs the code. This method receives device input. If the input command is "vote", the current option will be obtained from choicegroup. A vote object is constructed and sent to the resourceutility. addentry () method. This method will send the information to JSP, JSP will add a new vote to the record, and return an updated votesummary object. Then it will call the update () method:

Public void commandaction (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 = resourceutility. addentry (newvote );

Update (votesummary );
};
};

Votesummary

The votesummary object contains the status information of the current vote. It tracks all the voting numbers, the average voting, and maintains a vector of voting (you can get the voting information for each option ):

Public votesummary (string numvotes, string avgvote, vector votes)
{;
_ Numvotes = numvotes;
_ Avgvote = avgvote;
_ Votes = votes;
};

The votesummary object is created based on the XML returned by JSP to the MIDlet.

Resourceutility

The resourceutility class obtains XML Information from the remote server. It uses httpconnection to get XML from JSP, and then converts the XML into a votesummary object through xmlutil:

Public static votesummary getvotesummary ()
{;
String xml = loadvoteresults ();

Return convertxmltovotesummary (XML );
};

The getvotesummary () method above accesses this object. This method calls the loadvoteresults () and convertxmltovotesummary () methods in sequence. The loadvoteresults () method is as follows. It calls the backendcomms () method, which is used to add a vote for the background system:

Public static string loadvoteresults ()
{;
Return backendcomms (load_url ,"");
};
Private Static string backendcomms (string requesturl, string requeststring)
{;
Httpconnection = NULL;
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 first
Long contentlength = 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) inputchar );
};
};
Datainputstream. Close ();

}; Catch (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 describes the backendcomms () method. Start with the try-Catch Block. The first step is to open a read/write httpconnection to the server. As I have said above, this method gets XML and sends a write request to 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 an httpconnection implementation, we call the connector. open () method. This class contains static methods, which can generate corresponding interfaces for communication based on the connection string. In this example, we want to get an httpconnection, so we put the response of connector. open () into the httpconnection interface.

Once a request is sent, we can use the openinputstream () method of the httpconnection object to obtain the result inputstream from JSP:

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) inputchar );
};
};

Then you can read the length of the response content. If it is not found, you can still read it until you get an EOF or a wrong character. Each character read by datainputstream is added to stringbuffer. This stringbuffer contains a voting result in XML format. It will be sent back to the called method and then sent to the convertxmltovotesummary () method, as shown below:

Private Static votesummary convertxmltovotesummary (string XML)
{;
Inputstreamreader insr = new inputstreamreader (
New bytearrayinputstream (XML. getbytes ()));

Votesummary = NULL;

Try
{;
Votesummary = xmlutil. getvoteresults (insr );

}; Catch (ioexception IOE)
{;};

Return votesummary;
};

This method converts an XML string into a Java object, so that we can use the method to obtain data, rather than analyze data. We use the xmlutil. getvoteresults () method to perform this conversion. Before getting started with this method, we need to complete the resourceutility object. The last method is addentry (), which transfers a new vote to JSP. As mentioned above, for efficiency, it uses the backendcomms () method again:

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

The xmlutil object is used to convert the XML received by JSP into a votesummary object for application use. To complete the conversion, it must use an XML analyzer to parse the data. To reduce the overall size of the MIDlet, a lightweight analyzer should be used to minimize the overall size of the MIDlet. In this example, I use the kxml Analyzer of enhydra.

The following is the getvoteresults () method in this object. Let's take a look at how the conversion process is implemented:

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 xmlwriter (New outputstreamwriter
(System. Out )));

The first few rows set xmlparser and document objects. After these objects are created, the document. parse () method is called and xmlparser is transmitted as the parameter. The result document contains an XML message sent by JSP. If you are interested in the format of the authentication information, you can remove the comment mentioned above by calling ocument. Write 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 a document, we can use the DOM method to obtain the Element Object and obtain the value. The first two rows are used to move in the XML document to reach the nodes containing data. After obtaining the voteelement node, we can use the gettextfromelement () method to execute multiple commands to obtain the text node from the document and return its value:

Element choiceselement = voteelement. getelement ("Choices ");
Int childcount = choiceselement. getchildcount ();

The above two lines of code are used to obtain the number of nodes in the selected area. Using childcount, You can construct nodes without using the current number of votes. This is very important because you may need to join more votes in the future. With these calls, you can do this without modifying the Code:

For (INT I = 0; I <childcount; I ++)
{;
If (choiceselement. GetType (I) = xml. element)
{;
Choiceelement = choiceselement. getelement (I );

Choicevalue = gettextfromelement (choiceelement, "value ");
Choicename = gettextfromelement (choiceelement, "name ");
Choicevotes = gettextfromelement (choiceelement, "Number ");

Vote = new vote (choicevalue, choicename, choicevotes );

Ventries. addelement (vote );
};
};

Return new votesummary (numvotes, avgvote, ventries );

In this way, we can obtain the number of child elements, traverse them, and obtain the voting information. Some subnodes are element, while others are text nodes without data. In this example, We only care about elements, so we need to set the corresponding conditions in the loop. Each subelements is obtained from the option element and a vote object is constructed. The object contains values (used for calculation), names, and the number of votes. These vote objects are added to the vector in sequence. Finally, this method initializes a new votesummary object, which contains the above three information.

Private Static string gettextfromelement (element elementroot,
String elementname)
{;
String returntext = elementroot. getelement (elementname). gettext ();

Return returntext;
};

We use the gettextfromelement () method to make the code more readable. It goes deep into the tree structure and obtains the text node information.

Voter. jsp

The last element of this system is to simulate the JSP of the backend system. In this example, I created a simple JSP that uses class variables to track voting computing.

For details about JSP, see source code. It only tracks voting and returns data in XML format.

Key Points

This example illustrates how to interact with a server component through httpconnection. By sending a request, MIDP can communicate with JSP components through common http get/post calls. In this example, the call returns XML Information.

Using kxml analyzer, XML can be effectively converted into an object, and the graphics class can obtain data from this object. You should also note that in the application, choicegroup does not define the number of options, but is dynamically set through the server components.

Like any multi-layer development task, we need to consider how to effectively implement the Model-View-controller model and avoid creating redundant code. This idea is also reflected in this example. This model is JSP. View is the voteresults object that displays all data information. The Controller here is also the voteresults object, because it implements the commandlistener interface.

Communication

In this article, we mainly discuss a MIDP communication system that can generate HTTP requests. These requests can be from a known port using the standard protocol to any application-level protocol using the private protocol. The APIs can flexibly process these requests in a similar way.

What if you are in an area outside of coverage (for example, when you enter a tunnel) when interacting with remote machines? Unlike WAP, a phone with the MIDP function can continue to run its applications when it is in an area outside of coverage. This technology allows users to use offline functions and synchronize with online applications when they return to the coverage area. For example, a MIDP-based email application: You can continue to read and respond to emails that have been downloaded to the local RMS datastore. When you return to the coverage area, the reply information can be sent to the server and distributed to different recipients.

The current release of the j2rwireless toolkit does not support HTTPS. However, the developer version released earlier does support HTTPS. With the support of these APIs, you can trade shares or buy and sell on Java phones.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.