Address: http://www.javaresearch.org/article/54666.htm
As more mobile phones and personal digital assistants are integrated into the information highway, it is increasingly important to access websites from mobile devices. Java has created a precedent for Small and Medium-sized storage capacity of consumer devices. It is used to develop mobile phone, pager, and other micro-device applications. Program Ideal language.
In this article, we will learn how to send an http get request and an http post request to the server from a j2_client. Although this is only an article of the Nature Article But I still assume that the reader is familiar with the operating mechanism of Java, j2's, and Java midlets (MIDP application. We will use the MIDP short table of j2m's and use sun's wireless application development kit of j2m's to compile, configure, and test our applications. For the HTTP server, any WWW address can be accessed, but by default, we will use a simple Java Servlet to return the details of our HTTP request.
How can I use the j2_client to send HTTP requests to web servers and similar servers that support HTTP? The answer is to use a network class that can be found in the javax. microedition. Io package. This article will describe this question in detail.
Overview:
Design wireless network applications using j2s
. Send a hypertext GET request
. Send a hypertext POST request
. Program wireless networks using j2s
Java's network programming capability is quite robust. Java 2 Standard Edition (j2se) defines more than 100 interface programs, classes, and exceptions in Java. Io and java.net packages. These libraries provide powerful functions, but they are only applicable to traditional computer systems. These computer systems have powerful CPU processing capabilities, fast memory and persistent data storage, however, these are unrealistic on most wireless devices. Therefore, J2EE defines a subset of these functions and provides a set of Fixed Packages for network and file access-javax. microedition. Io packages. Due to the wide variety of mobile devices, this package only defines a set of interfaces, leaving the actual application interface implementation for each mobile device vendor. This finds an optimal balance between portability and specific features of the device.
The abstract network and file input and output framework defined in the javax. microedition. Io class are called the General connection framework (GCF ). GCF defines a set of abstract content to describe different communication methods. The highest level abstraction is called connection and six interfaces are declared (four are direct and two are indirect ). These seven interfaces constitute a part of the cldc of j2's. cldc is the configuration used by most wireless devices that can use Java. This configuration is designed to provide public network and file input and output capabilities for all cldc devices (such as mobile phones, two-way pagers, and low-end PDAs. Although GCF is designed for public networks and file input and output frameworks, the producer does not require implementation of all interfaces declared in GCF. Some manufacturers can decide to only support socket connections, while other manufacturers can choose to only support datagram-based communication. To facilitate portability across similar devices, the MIDP specification requires all MIDP devices to implement the httpconnection interface. Httpconnection is not part of GCF, but it is derived from contentconnection, an interface of GCF. We will use the httpconnection interface to construct our sample application.
Send an http get request
This section will focus on the Procedures Code In the next section, we will only describe the universal connection framework interface and httpconnection interface used to send HTTP requests and retrieve responses returned by the server. For the program code for creating the MIDP user interface, see the appendix.
First, we need to define a method to put the code used to send an http get request. Some operations in this method may throw an ioexception, so we will throw this exception to the call method.
Public String sendhttpget (string URL) throws ioexception {
Httpconnection hcon = NULL;
Datainputstream Dis = NULL;
Stringbuffer message = "";
Try {
The first step is to use the connector class to open a connection to the server, which is the key to GCF. We will forcibly convert this connection to the required type. In this example, it is the httpconnection type.
Hcon = (httpconnection) connector. Open (URL );
Next, we get a datainputstream on httpconnection, which allows us to read server response data with one character and one character.
Dis = new datainputstream (hcon. openinputstream ());
Using the read () method of datainputstream, every character in the server response is centralized and put into the stringbuffer object.
Int ch;
While (CH = dis. Read ())! =-1 ){
Message = message. append (char) CH );
}
Finally, the connection object is cleared to save the resource, and the information is returned from this method.
} Finally {
If (hcon! = NULL) hcon. Close ();
If (DIS! = NULL) dis. Close ();
} // End the try/finally code segment
Return message. tostring ();
} // End sendgetrequest (string)
How to send an http post request
As you can imagine, the process of sending an http post request is actually very similar to sending a GET request. We will modify an existing command and add a few new commands, add an additional object from the universal connection framework and an additional stringbuffer object to send the POST request weight content to the server. The remaining commands remain unchanged.
Copy the sendhttpget () method we just created, paste it into the same class file, and rename it sendhttppost (). Now, we will modify this new method to send an http post request to the server. Add two new variable descriptions at the top of the method. Declare a variable of the dataoutputstream type and a variable of the other string type. We will use the dataoutputstream object to send the POST Request body that exists in the string variable to the server.
Dataoutputstream dos = NULL;
String requestbody = NULL;
Modify the connector. open () command to include another parameter, indicating that the connection will allow the client to read and write data on the server through the connection.
Hcon = (httpconnection) connector. Open (URL, connector. read_write );
Set the request method used by the httpconnection object to post (the default method is get ).
Hcon. setrequestmethod (httpconnection. post );
Obtain a dataoutputstream object for the existing HTTP connection.
DOS = HC. opendataoutputstream ();
Declare a byte array and retrieve a byte array from the requestbody string for initialization. Write the buffer of dataoutputstream into the byte array.
Byte [] byterequest = requestbody. getbytes ();
For (INT I = 0; I <byterequest. length; I ++ ){
Dos. writebyte (byterequest [I]);
} // End for (INT I = 0; I <byterequest. length; I ++)
Dos. Flush (); // contains this sentence. Unexpected results may occur in some settings.
The intention of calling the flush () method is to send written data to the buffer zone of the dataoutputstream server. On some phones, this operation works normally. On other phones, it causes the HTTP Request Transfer-encoding to be set to "chunked ", some random characters are placed before and after the request itself. So how can we solve this problem? This method is actually not required at all. In the next row, the server connection is opened (through openinputstream () and the buffer zone is automatically entered. Therefore, you 'd better not call the buffer's flush () method. The rest of this method remains unchanged, except that the dataoutputstream object must be disabled in the finally {} block.
} Finally {
If (HC! = NULL) HC. Close ();
If (DIS! = NULL) dis. Close ();
If (dos! = NULL) dis. Close ();
} // End try/finally
This is all the program code! See the program code that comes with this article.
With the increasing popularity of wireless devices that can use international networks and support networks, Java and j2's importance is also growing. Because HTTP is the only network protocol currently supported by all devices that comply with MIDP specifications, it is also the best candidate for developing wireless network applications.
In this article, we explored the basic structure of wireless network programming and several core issues. We learned how to call two of the most common HTTP request methods: Get and post. Still in its early stages of development, and wireless devices will soon become popular. Therefore, developers who are interested in wireless network programming will be given a great opportunity.
Appendix:
/*
* Httpmidlet. Java
*/
Import javax. microedition. MIDlet .*;
Import javax. microedition. lcdui .*;
Import javax. microedition. Io .*;
Import java. Io .*;
Public class httpmidlet extends MIDlet implements commandlistener {
// Use the default URL. You can change this value from the graphic user interface.
Private Static string defaulturl = "http: // localhost: 8080/test/servlet/echoservlet ";
// Master MIDP display
Private display mydisplay = NULL;
// Graphical user interface component for URL input
Private form requestscreen;
Private textfield requestfield;
// Graphical user interface component used for request submission
Private list;
Private string [] menuitems;
// Graphical user interface component used to display server responses
Private form resultscreen;
Private stringitem resultfield;
// The "send" button for requestscreen
Command sendcommand;
// The "exit" button for requestscreen
Command exitcommand;
// The "back" button for requestscreen
Command backcommand;
Public httpmidlet (){
// Initialize the graphical user interface component
Mydisplay = display. getdisplay (this );
Sendcommand = new command ("send", command. OK, 1 );
Exitcommand = new command ("exit", command. OK, 1 );
Backcommand = new command ("back", command. OK, 1 );
// Display the requested URL
Requestscreen = new form ("type in a URL :");
Requestfield = new textfield (null, defaulturl, 100, textfield. url );
Requestscreen. append (requestfield );
Requestscreen. addcommand (sendcommand );
Requestscreen. addcommand (exitcommand );
Requestscreen. setcommandlistener (this );
// Select the desired HTTP Request Method
Menuitems = new string [] {"GET request", "POST request "};
List = new list ("select an HTTP Method:", list. implicit, menuitems, null );
List. setcommandlistener (this );
// The information first received from the server
Resultscreen = new form ("server response :");
Resultscreen. addcommand (backcommand );
Resultscreen. setcommandlistener (this );
} // End httpmidlet ()
Public void Startapp (){
Mydisplay. setcurrent (requestscreen );
} // End Startapp ()
Public void commandaction (command COM, displayable disp ){
// When the user clicks the "send" button
If (COM = sendcommand ){
Mydisplay. setcurrent (list );
} Else if (COM = backcommand ){
Requestfield. setstring (defaulturl );
Mydisplay. setcurrent (requestscreen );
} Else if (COM = exitcommand ){
Destroyapp (true );
Yydestroyed ();
} // End if (COM = sendcommand)
If (disp = List & COM = List. select_command ){
String result;
If (list. getselectedindex () = 0) // send a GET request to the server
Result = sendhttpget (requestfield. getstring ());
Else // send a POST request to the server
Result = sendhttppost (requestfield. getstring ());
Resultfield = new stringitem (null, result );
Resultscreen. append (resultfield );
Mydisplay. setcurrent (resultscreen );
} // End if (Dis = List & COM = List. select_command)
} // End commandaction (command, displayable)
Private string sendhttpget (string URL)
{
Httpconnection hcon = NULL;
Datainputstream Dis = NULL;
Stringbuffer responsemessage = new stringbuffer ();
Try {
// Standard httpconnection with read permission
Hcon = (httpconnection) connector. Open (URL );
// Obtain a datainputstream from httpconnection
Dis = new datainputstream (hcon. openinputstream ());
// Retrieve the response from the server
Int ch;
While (CH = dis. Read ())! =-1 ){
Responsemessage. append (char) CH );
} // End while (CH = dis. Read ())! =-1)
}
Catch (exception E)
{
E. printstacktrace ();
Responsemessage. append ("error ");
} Finally {
Try {
If (hcon! = NULL) hcon. Close ();
If (DIS! = NULL) dis. Close ();
} Catch (ioexception IOE ){
IOE. printstacktrace ();
} // End try/catch
} // End try/catch/finally
Return responsemessage. tostring ();
} // End sendhttpget (string)
Private string sendhttppost (string URL)
{
Httpconnection hcon = NULL;
Datainputstream Dis = NULL;
Dataoutputstream dos = NULL;
Stringbuffer responsemessage = new stringbuffer ();
// Request body
String requeststring = "this is a post .";
Try {
// Httpconnection with read/write permission
Hcon = (httpconnection) connector. Open (URL, connector. read_write );
// SET THE REQUEST METHOD TO POST
Hcon. setrequestmethod (httpconnection. post );
// Obtain the dataoutputstream that sends the request string
DOS = hcon. opendataoutputstream ();
Byte [] request_body = requeststring. getbytes ();
// Send the request string to the server
For (INT I = 0; I <request_body.length; I ++ ){
Dos. writebyte (request_body [I]);
} // End for (INT I = 0; I <request_body.length; I ++)
// Obtain the datainputstream as the server response
Dis = new datainputstream (hcon. openinputstream ());
// Retrieve the response from the server
Int ch;
While (CH = dis. Read ())! =-1 ){
Responsemessage. append (char) CH );
} // End while (CH = dis. Read ())! =-1 ){
}
Catch (exception E)
{
E. printstacktrace ();
Responsemessage. append ("error ");
}
Finally {
// Release the input/output stream and HTTP Connection
Try {
If (hcon! = NULL) hcon. Close ();
If (DIS! = NULL) dis. Close ();
If (dos! = NULL) dos. Close ();
} Catch (ioexception IOE ){
IOE. printstacktrace ();
} // End try/catch
} // End try/catch/finally
Return responsemessage. tostring ();
} // End sendhttppost (string)
Public void pauseapp (){
} // End pauseapp ()
Public void destroyapp (Boolean unconditional ){
Mydisplay = NULL;
Requestscreen = NULL;
Requestfield = NULL;
Resultscreen = NULL;
Resultfield = NULL;
} // End destroyapp (Boolean)
} // End httpmidlet