Implement the HTTP protocol on a wireless J2EE device

Source: Internet
Author: User

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 storage capacity for consumer devices. It is an ideal language for developing mobile phone, pager, and other micro-device applications.
In this article, we will learn how to send an httpget request and an httppost request to the server from a j2_client. Although this is only an article about the nature, I still assume that the reader is familiar with Java, j2s, and the operating mechanism of javamidlets (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 assumervlet 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. Java2 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 httpget request

This section focuses on program 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 the httpget request. Some operations in this method may throw an ioexception, so we will throw this exception to the call method.

Publicstringsendhttpget (stringurl) throwsioexception {;
Httpconnectionhcon = NULL;
Datainputstreamdis = NULL;
Stringbuffermessage = "";
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 = newdatainputstream (hcon. openinputstream ());

Using the read () method of datainputstream, every character in the server response is centralized and put into the stringbuffer object.

Intch;
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
Returnmessage. tostring ();
}; // End sendgetrequest (string)

How to send an httppost request

As you can imagine, the process of sending an httppost request is 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 httppost 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.

Dataoutputstreamdos = NULL;
Stringrequestbody = 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 (INTI = 0; I <byterequest. length; I ++ ){;
Dos. writebyte (byterequest [I]);
}; // End for (INTI = 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 closed in the finally {;}; statement 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
*/
Importjavax. microedition. MIDlet .*;
Importjavax. microedition. lcdui .*;
Importjavax. microedition. Io .*;
Importjava. Io .*;

Publicclasshttpmidletextendsmidletimplementscommandlistener {;
// Use the default URL. You can change this value from the graphic user interface.
Privatestaticstringdefaulturl = "http: // localhost: 8080/test/servlet/echoservlet ";;

// Master MIDP display
Privatedisplaymydisplay = NULL;

// Graphical user interface component for URL input
Privateformrequestscreen;
Privatetextfieldrequestfield;

// Graphical user interface component used for request submission
Privatelistlist;
Privatestring [] menuitems;

// Graphical user interface component used to display server responses
Privateformresultscreen;
Privatestringitemresultfield;

// The "send" button for requestscreen
Commandsendcommand;
// The "exit" button for requestscreen
Commandexitcommand;
// The "back" button for requestscreen
Commandbackcommand;

Publichttpmidlet (){;
// Initialize the graphical user interface component
Mydisplay = display. getdisplay (this );
Sendcommand = newcommand ("send", command. OK, 1 );
Exitcommand = newcommand ("exit", command. OK, 1 );
Backcommand = newcommand ("back", command. OK, 1 );

// Display the requested URL
Requestscreen = newform ("typeinaurl :");
Requestfield = newtextfield (null, defaulturl, 100, textfield. url );
Requestscreen. append (requestfield );
Requestscreen. addcommand (sendcommand );
Requestscreen. addcommand (exitcommand );
Requestscreen. setcommandlistener (this );

// Select the desired HTTP Request Method
Menuitems = newstring [] {; "getrequest", "postrequest "};;
List = newlist ("selectanhttpmethod:", list. implicit, menuitems, null );
List. setcommandlistener (this );

// The information first received from the server
Resultscreen = newform ("serverresponse :");
Resultscreen. addcommand (backcommand );
Resultscreen. setcommandlistener (this );

}; // End httpmidlet ()

Publicvoidstartapp (){;
Mydisplay. setcurrent (requestscreen );
}; // End Startapp ()

Publicvoidcommandaction (commandcom, displayabledisp ){;
// When the user clicks the "send" button
If (COM = sendcommand ){;
Mydisplay. setcurrent (list );
}; Elseif (COM = backcommand ){;
Requestfield. setstring (defaulturl );
Mydisplay. setcurrent (requestscreen );
}; Elseif (COM = exitcommand ){;
Destroyapp (true );
Yydestroyed ();
}; // End if (COM = sendcommand)

If (disp = List & COM = List. select_command ){;

Stringresult;

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 = newstringitem (null, result );
Resultscreen. append (resultfield );
Mydisplay. setcurrent (resultscreen );
}; // End if (Dis = List & COM = List. select_command)
}; // End commandaction (command, displayable)

Privatestringsendhttpget (stringurl)
{;
Httpconnectionhcon = NULL;
Datainputstreamdis = NULL;
Stringbufferresponsemessage = newstringbuffer ();

Try {;
// Standard httpconnection with read permission
Hcon = (httpconnection) connector. Open (URL );

// Obtain a datainputstream from httpconnection
Dis = newdatainputstream (hcon. openinputstream ());

// Retrieve the response from the server
Intch;
While (CH = dis. Read ())! =-1 ){;
Responsemessage. append (char) CH );
}; // End while (CH = dis. Read ())! =-1)
};
Catch (effectione)
{;
E. printstacktrace ();
Responsemessage. append ("error ");
}; Finally {;
Try {;
If (hcon! = NULL) hcon. Close ();
If (DIS! = NULL) dis. Close ();
}; Catch (ioexceptionioe ){;
IOE. printstacktrace ();
}; // End try/catch
}; // End try/catch/finally
Returnresponsemessage. tostring ();
}; // End sendhttpget (string)

Privatestringsendhttppost (stringurl)
{;
Httpconnectionhcon = NULL;
Datainputstreamdis = NULL;
Dataoutputstreamdos = NULL;
Stringbufferresponsemessage = newstringbuffer ();
// Request body
Stringrequeststring = "thisisapost .";

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 (INTI = 0; I <request_body.length; I ++ ){;
Dos. writebyte (request_body [I]);
}; // End for (INTI = 0; I <request_body.length; I ++)

// Obtain the datainputstream as the server response
Dis = newdatainputstream (hcon. openinputstream ());

// Retrieve the response from the server
Intch;
While (CH = dis. Read ())! =-1 ){;
Responsemessage. append (char) CH );
}; // End while (CH = dis. Read ())! =-1 ){;
};
Catch (effectione)
{;
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 (ioexceptionioe ){;
IOE. printstacktrace ();
}; // End try/catch
}; // End try/catch/finally
Returnresponsemessage. tostring ();
}; // End sendhttppost (string)

Publicvoidpauseapp (){;
}; // End pauseapp ()

Publicvoiddestroyapp (booleanunconditional ){;
Mydisplay = NULL;
Requestscreen = NULL;
Requestfield = NULL;
Resultscreen = NULL;
Resultfield = NULL;
}; // End destroyapp (Boolean)
}; // End httpmidlet

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.