As more and more mobile phones and personal digital assistants began to integrate into the information highway, accessing the Web site from mobile devices is getting more and more important. Java created a primary river in small storage capacity in consumer equipment, which is an ideal language for developing mobile phones, pager, and other micro device applications. In this article, we will learn how to send an HTTP GET request from a J2ME client and an HTTP POST request. Although this is just an article discussed nature, I still assume that readers are familiar with Java, J2ME, and Java MIDLETS (MIDP applications) operation mechanism. We will use J2ME's MIDP and use Sun's J2ME wireless application development kit compile, configure, and test our app. For HTTP servers, any WWW address can be accessed, but we will use a simple Java Servlet to return to our HTTP request details. How do I use the J2ME client to send HTTP requests to the web server and a similar support HTTP server? The answer is to use the network class of J2ME that can be found in the Javax.microedition.IO package. This article wants to specifically explain this problem. This article Overview: Use the J2ME to design a wireless network application. Send a hypertext GET request. Send a hypertext POST request. The network programming capability of Java using J2ME for wireless network programming is quite robust. Java 2 Standard Edition (J2SE) defines more than 100 interface programs, classes, and exceptions in java.io and java.net packages. The functions implemented through these libraries are very powerful, but this only applies to traditional computer systems, which have powerful CPU processing capabilities, fast memory, and persistent data storage, but these are on most wireless devices. not realistic. Therefore, J2ME defines the subset of these functions and provides a fixed package for network and file access --- javax.microedition.io package. Due to a wide variety of mobile devices, this package only defines a set of interfaces, and left the actual application interface for each mobile device supplier. This has found an optimal balance point in the application of portability and specific features of equipment. Define Abstract Networks and File Input Output Framers in the Javax.microedition.IO class, called General Connection Framework (GCF). GCF defines a set of content related to the different communication methods. The most advanced abstraction is called Connection, as well as six interfaces (four are direct, two are indirect). These seven interfaces constitute a part of the CLDC of J2ME, and CLDC is most of the configuration that can use Java wireless devices. The purpose of designing this configuration is to provide public network and file input and output capabilities for all CLDC devices (mobile phones, two-way pager, low-end PDA, etc.). Although the purpose of GCF is the public network and file input output frame, manufacturers do not require all interfaces declared in GCF. Some manufacturers can decide to only support Socket connections, while other manufacturers can choose to support only datagram. In order to promote portability across similar devices, the MIDP specification requires all MIDP devices to implement HTTPConnection interfaces. HttpConnection is not part of the GCF, but it is derived from a interface ContentConnection from GCF. We will construct our sample application using the HTTPConnection interface. Send an HTTP GET Request This section will focus on program code. In the next section, we will only tell the HTTP request and retrieve the response universal connection frame interface and HTTPConnection interface returned by the server. See the appendix for program code for creating a MIDP user interface.
Let's first define a method to place the code to send the HTTP GET request. Because some of this method has potential to throw IOException, we will throw such an accident to the calling method. Public STRING Sendhttpget (String URL) THROWS IEXCEPTION {httpConnection hcon = null; databasePutStream DIS = NULL; STRINGFFER Message = ""; try {First Step is to open a connection to the server using the Connector class, which is the key to GCF. We will convert this connection to the type of desired, in this case for the httpConnection type.
HCON = (httpConnection) Connector.open (URL); Next, we get a DataInputStream on HTTPConnection, allowing us to respond to data of a character of a character.
DIS = New DataInputStream (HCON.OPENINPUTSTREAM ()); using DataInputStream's read () method, each character of the server response is set up in the StringBuffer object.
INT Ch; While ((ch = disp.read ())! = -1) {message = message.Append (char) ch);} Finally, the connection object is cleared to save resources, and the information is returned from this method. .
} finally {if (hcon! = null) hcon.close (); if (disguise = null) disgclose ();} // End Try / finally code segment Return Message.toString ();} // End SendgetRequest (String) How to send an HTTP POST request You can imagine that the process of sending an HTTP POST request is actually similar to sending a GET request. We will modify an existing command to add a small number of new commands, and add an additional object from the General Connection Frame and an additional StringBuffer object to the server to the server. The rest of the command will remain unchanged. Copy the SendhttpGet () method we have created, paste it into the same class file, and rename Sendhttppost (). Now, we will modify this new method to send an HTTP POST request to the server. Two new variables are added to the top of the method. Declare a variable for DataOutputStream and another String type variable. We will send the POST request body existing in the string variable to the server using the DataTPutStream object.
DataOutputStream DOS = NULL; STRING RequestBody = NULL; Modifying the connection connector.Open () command contains another parameter indicating that the connection will allow the client to read and write over the server.
HCON = (httpConnection) Connector.open (URL, Connector.Read_write); Setting the request method used by the HTTPConnection object is POST (the default method is Get).
Hcon.setRequestMethod (httpconnection.post); gets a DataOutputStream object for existing HTTP connections.
DOS = hc.opendataoutputstream (); declares a byte array and initializes an array of byte arrays from the RequestBody string. Then write the buffer of DataOutputStream into the bytecode. Byte [] Byterequest = RequestBody.getbytes (); for (int i = 0; i } finally {if (hc! = null) hc.close (); if (disguise = null) Dis.close (); if (dos! = null) disgic ();} // End Try / Finally That is to all program code! And see the program code included after this article. With the increasing increase in wireless devices that can use the Internet and support networks, the importance of Java and J2ME is also constantly increasing. Because the HTTP protocol is currently only, all network protocols supported by the MIDP specification, it is also the best candidate for developing wireless web applications. In this article, we explore the basic structure of wireless network programming and several core questions, we have seen how to call two most common HTTP request methods: GET and POST. J2ME is still in its early development, and wireless devices will also get a large area of popularization. Therefore, all the developers who have a wireless network programming will get a good opportunity for the big box. 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. The user can change this value from the graphical user interface, private static string defaultURL = "http: // localhost: 8080 / test / servlet / echoservlet"; // Main MIDP Display Private Display MyDisplay = NULL; // Enter the graphical user interface component of the URL private Form requestScreen; private TextField requestField; // a graphical user interface components commit request private List list; private String [] menuItems; graphical user interface components for displaying a private Form resultScreen // server response; private StringItem resultField; / / Used for RequestScreen "SEND" button command sendcommand; // uses "EXIT" button for RequestScreen Command EXITCOMMAND; / / "Back" button for RequestScreen; public httpmidlet () {// Initialization graphical user interface components 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); // show URLrequestScreen request = new Form ( "Type in a URL:"); requestField = new TextField (null, defaultURL, 100, TextField.URL); requestScreen.append (requestField); requestScreen .addcommand; requestscreen.addcommand (exitcommand); RequestScreen.SetCommandListener This); // Select the desired HTTP request method MENUIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIITEMS = new string [] {"get recuest"}; list = new list ("SELECT AN HTTP Method:", List.Implicit, MenuItems, NULL List.setcommandlistener (this); // First received information received from the server ResultScreen = New Form ("Server Response:"); ResultScreen.Addcommand (BACKCREEN.SETCOMMANDLISTENER (this);} // End httpmIdlet () public void startapp () {mYDisplay.setCurrent (RequestScreen);} // End StartApp () public void command (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); notifyDestroyed ();} // end of if (com == sendCommand) if (disp == List && COM == List.select_command) {string result; if (list.getSelectedIndex () == 0) // Send a GET request to server result = sendhttpget (Requestfield.getstring ()); Else // Send one POST request to the server result = sendHttpPost (requestField.getString ()); resultField = new StringItem (null, result); resultScreen.append (resultField); myDisplay.setCurrent (resultScreen);} // end of 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 {// READ permission to use standard HttpConnectionhcon = (HttpConnection) Connector.open (url); // get a DataInputStreamdis = new DataInputStream (hcon.openInputStream ()) from HttpConnection; // int ch retrieved from the server in response; while ((ch = dis . Read ())! = -1) {responseMessage.Append ((char) ch);} // End While ((ch = dish ())! = -1)} Catch (Exception E) {E.PrintStackTrace (); responseMessage.Append ("error");} finally {try {if (hcon! = null) hcon.close (); if (disguise = null) disgiclose ();} catch (ooException ooe) { ioe.printStackTrace ();} // end try / catch} // end try / catch / finallyreturn responseMessage.toString ();} // end sendHttpGet (String) private String sendHttpPost (String url) {HttpConnection hcon = null; DataInputStream DIS = NULL; DataoutputStream DOS = NULL; STRINGBUFFER RESPONSEMESSAGE = New StringBuffer ();