Network Communication Skills between mobile phones and servlets (apply for points)

Source: Internet
Author: User
Tags keep alive
As more mobile phones and personal digital assistants are integrated into the information highway, it is increasingly important to access websites from mobile devices. Only after you implement the function of communication between a mobile device and a non-mobile device can the mobile device application you designed be truly useful.

In this article, we will use a simple example to learn how to implement network communication between a mobile phone and a servlet. The program is compiled, configured, and tested by tomcat4.0.6, MIDP table of j2's and Sun's wireless application development kit of j2's, and the Chinese characters are displayed normally on the mobile phone simulator.

Some reference books all talk about network programming of j2's, but I feel that most of them are similar, and there are very few complete mobile client programs and Servlet server programs, although there are many methods for communication between mobile phones and servlets, I think datainputstream is a simple method for communication between mobile phones and servlets. readutf and dataoutputstream. writeutf pairing. For example, you can use dataoutputstream to send data on the mobile phone in the connection output stream. writeutf writes multiple parameters in sequence. Correspondingly, the servlet opens the request input stream (request. getinputstream) with datainputstream. readutf.

The returned parameters are the same. servlet uses response. getoutputstream to open the output stream and write the returned values in sequence. Then, the mobile phone can open the connection output stream and read it. As for multiple parameters and multiple return values, there is no problem, but writeutf and readutf are used multiple times. Readers can refer to the comments in the program and the running results to understand how the mobile phone and Servlet transmit and return parameters and how network communication is implemented.

Mobile client:

Import javax. microedition. MIDlet .*;
Import javax. microedition. lcdui .*;
Import javax. microedition. Io .*;
Import java. Io .*;
Public class clientapp extends
MIDlet implements commandlistener
{
Display display; textfield TF1,
TF2; string tf1str, tf2str;
Form inputform, returnform;
Command cmdsend, cmdback;
Final Static string defaulturl =
& Quot; http: // localhost: 8080/Examples
/Servlet/servletapp ";
Public clientapp ()
{
Display = display. getdisplay (this );
TF1 = new textfield ("input first Param :",
"Ludongfang", 20, textfield. Any );
TF2 = new textfield ("input second Param :",
"Wang taoqun", 20, textfield. Any );
Cmdsend = new command ("send", command. screen, 1 );
Cmdback = new command ("back", command. screen, 1 );
Inputform = new form ("PLS input the param :");
Inputform. append (TF1); inputform. append (TF2 );
Inputform. addcommand (cmdsend );
Inputform. setcommandlistener (this );
}
Public void Startapp ()
Throws midletstatechangeexception
{
Display. setcurrent (inputform );
}
Public void invokeservlet (string URL)
Throws ioexception
{
Httpconnection Hc = NULL;
Dataoutputstream dos = NULL;
Datainputstream Dis = NULL;
Try {
Hc = (httpconnection) connector. Open
(URL, connector. read_write );
// Set Request attributes
HC. setrequestmethod (httpconnection. post );
// Set the POST request method. The default request method is get.
HC. setrequestproperty
("If-modified-since", "15 Oct
2003 08:47:14 GMT ");
HC. setrequestproperty ("User-Agent ",
"Profile/MIDP-1.0 configuration/CLDC-1.0 ");
HC. setrequestproperty
("Content-language", "En-ca ");
HC. setrequestproperty
("Content-Type", "Application
/X-WWW-form-urlencoded ");
HC. setrequestproperty
("Connection", "keep-alive ");
// The Connection header can control the MIDlet
Keep the "Keep Alive" feature with the Web server.
"Keep Alive" Features
Always use the same HTTP connection with the Web server to transmit data multiple times.
(In general, HTTP is a connectionless protocol,
The connection will be disconnected after each data transmission,
The connection will be established again before the next data transmission)
// Send request parameters to Servlet
DOS = HC. opendataoutputstream ();
Dos. writeutf (tf1str );
Dos. writeutf (tf2str );
// Send request parameters to Servlet
System. Out. println
("The first parameter passed to servlet by the mobile phone is:" + tf1str );
// Main debugging function,
The debugging result is displayed on the wtk console.
System. Out. println
("The first parameter passed to servlet by the mobile phone is:" + tf2str );
Dos. Flush (); dos. Close ();
// Receives servlet response data
DS = new datainputstream
(HC. openinputstream ());
String return1str = dis. readutf ();
String return2str = dis. readutf ();
System. Out. println
("The first parameter sent from the servlet received by the mobile phone is :"
+ Return1str );
// Main debugging function,
The debugging result is displayed on the wtk console.
System. Out. println
("The second parameter sent from the servlet received by the mobile phone is:
"+ Return2str );
Returnform = new form ("returned result ");
Returnform. append (return1str );
Returnform. append ("/N ");
// Append the returned result to resultform
Returnform. append (return2str );
Returnform. addcommand (cmdback );
Returnform. setcommandlistener (this );
} Finally {
If (DIS! = NULL) {dis. Close ();
}
If (dos! = NULL) {dos. Close ();
}
If (HC! = NULL) {HC. Close ();
}
}
Display. setcurrent (returnform );
}
Public void pauseapp ()
{
}
Public void destroyapp
(Boolean unconditional)
{
}
Public void commandaction
(Command C, displayable D)
{
If (C = cmdback) {display. setcurrent (inputform );
}
If (C = cmdsend) {tf1str =
Tf1.getstring (); tf2str =
Tf2.getstring ();
Try {invokeservlet (defaulturl );
} Catch (exception E)
{
System. Out. println (E. getmessage ());
}
}
}
}

Servlet Server:

Import java. Io .*;
Import java. SQL .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Public class servletapp extends httpservlet
{
Public void doget
(Httpservletrequest request,
Httpservletresponse response)
Throws ioexception, servletexception
{
Response. setcontenttype
("Text/html; charset = GBK ");
// Set response attributes
// Receives client requests
Inputstream is =
Request. getinputstream ();
Datainputstream Dis =
New datainputstream (is );
String tf1str = dis. readutf ();
String tf2str = dis. readutf ();
System. Out. println
("The first parameter that the servlet client receives from the mobile phone is:
"+ Tf1str );
// Main debugging function,
The debugging result is displayed in the DOS Startup window of Tomcat.
System. Out. println
("The second parameter that the servlet client receives from the mobile phone is:
"+ Tf2str );
// Process the received Parameters
String return1str =
Tf1str. Concat (": Good morning! ");
// Connect the string after the received Parameter
String return2str =
Tf2str. Concat (": Good evening! ");
// Send the processed parameters to the mobile phone
Dataoutputstream dos =
New dataoutputstream
(Response. getoutputstream ());
Dos. writeutf (return1str );
Dos. writeutf (return2str );
System. Out. println
("The first parameter passed by servlet to the mobile phone is :"
+ Return1str );
System. Out. println
("The second parameter passed by servlet to the mobile phone is :"
+ Return2str );
}
Public void dopost
(Httpservletrequest request,
Httpservletresponse response)
Throws
Servletexception, ioexception
{
Doget (request, response );
}
Public void destroy ()
{
}
// Clear Resources

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.