Hypertext transfer protocol on wireless J2ME device

xiaoxiao2021-03-06  17

As more and more mobile phones and personal digital assistants began to integrate into the information highway, the Web site accessed from mobile devices becomes increasing

The more important. Java has created a primary river in small storage capacity in consumer equipment, which is used to develop mobile phones, pager and other miniature device applications.

Ideal language. In this article, we will learn how to send an HTTP GET request from a J2ME client and an HTTP POST.

begging. Although this is just a discussion of the nature, I still assume that the reader is already familiar with Java, J2ME, and Java MIDLETS (MIDP should

The operation mechanism of the program). We will use J2ME's MIDP brief and use Sun's J2ME wireless application development kit compile.

Set and test our app. For HTTP servers, any WWW address can be accessed, but it will use a simple only by default.

Java servlets are returned 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

Javax.microEdition.IOOG package can be found in the J2ME network class. 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 interfaces in java.io and java.net packages

Programs, classes, and exceptions. The functionality implemented through these libraries is very powerful, but this only applies to traditional computer systems, these computer systems have

Powerful CPU processing capabilities, fast memory, and persistent data storage, but these are unrealistic on most wireless devices. therefore,

J2ME defines the subset of these functions and provides a fixed package for network and file access - Javax.microedition.io program

package. Due to a wide variety of mobile devices, this package only defines a set of interfaces, and left actuals for each mobile device supplier vendor.

Application interface implementation. This has found an optimal balance point in the application of portability and specific features of equipment. Defining Abstract Networks and File Input Output Framers in Javax.microedition.IO classes called universal connection framework (Generic Connection

Framework, referred to as GCF). GCF defines a set of content related to the different communication methods. The most advanced abstraction is called

The Connection also declares that six interfaces (four are direct, both are indirect). These seven interfaces constitute J2ME CLDC

Part part, CLDC is most of the configuration used by wireless devices that can use Java. The purpose of designing this configuration is to all CLDC devices

(Portable Phone, Bidirectional Press, Low-end PDA, etc.) Provide public network and file input and output capabilities. Although the purpose of GCF is a public network

And file input and output framework, but manufacturers do not require all interfaces declared in GCF. Some manufacturers can decide to only support Socket even

Connect, while other manufacturers can choose to support only datagram based communication. In order to promote portability across similar devices, MIDP specifications require all

The MIDP device implements the HTTPConnection interface. HTTPConnection is not part of GCF, but it is an interface from GCF

CONTENTCONNECTION is derived. 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 response to send HTTP requests and retrieve the response returned by the server.

Use the connection frame interface and the HTTPConnection interface. 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 ioException {httpConnection hcon = null; dataputstream dis = null; stringbuffer message = ";" Try {

The first step is to open a connection to the server using the Connector class, which is the key to the GCF. We will enforce this connection into need

The first step is to use

CONNECTOR

Class opens a connection to the server, this is

GCF

key. We will enforce this connection into need

The type of type is httpConnection type in this example.

HCON = (httpConnection) Connector.open (URL);

Next, we get a DataInputStream on HTTPConnection, allowing us to read a character of a character.

Next, we get

HttpConnection

On one

DataInputStream

Allows us to read a character of a character

Response data.

DIS = New DataInputStream (HCON.OpenInputStream ());

Using DataInputStream's read () method, each character of the server responded is set up in the StringBuffer object.

INT Ch; While ((ch = dish ())! = -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 one

Existing commands, add a small number of new commands, and add an additional object from the general connection frame and an additional StringBuffer object

POST requests the content of the weight 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 (). right now I am

They 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 one

Types of variables for DataOutputStream and variables for another String type. We will use the DataOutputStream object to exist in words.

The POST request body in string variable is sent to the server.

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.sequestMethod (httpConnection.post);

Get a DataOutputStream object for existing HTTP connections.

DOS = hc.opendataoutputstream ();

Declare a byte array and initialize by retrieving bytes from a REQUESTBODY string. Then put DataOutputStream

Declare a byte array and from a retrieval from

RequestBody

The byte array initialization of the string.

Then put

DataOutputstream

The buffer write into the byte array.

Byte [] Byterequest = RequestBody.getbytes (); for (int i = 0; i

The intent to call the flush () method is to send the data that has been written to the server of DataOutputStream servers. In some callings

transfer

Flush ()

The intent of the method is to send the data that has been written to

DataOutputstream

The server's buffer.

In some callings

On, this operation works fine, on other phones, it causes the transfer - encoding of HTTP requests to "Chunked", there is one

Some random characters are placed in front and behind the request itself. How do you deal with this problem? This method call is actually not required.

In the next line, the server connection opens (via OpenInputStream (), will automatically enter the buffer. So you'd better not adjust

Use the flush () method of the buffer. The rest of this method remains unchanged, except for the DataOutputStream object must be in the Finally {} statement

close.

} finally {if (hc! = null) hc.close (); if (disguise = null) Dis.close (); if (dos! = null) disgoclose ();} // End TRY / FINALLY

This is all the program code! And see the program code included after this article. With the increasing increase in wireless devices that can use the international Internet and support network, the importance of Java and J2ME is constantly changing.

This is all the program code

!

And please refer to the program code included in this article.

With the increasing popularity of wireless devices that can use international Internet and support networks,

Java

with

J2ME

The importance is also constant

Big. Because the HTTP protocol is currently currently only, it is also used to develop wireless networks by all network protocols supported by the MIDP specification.

The best candidate for the application. 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 HTTPs.

Method: GET and POST. J2ME is still in its early development, and wireless devices will also get a large area of ​​popularization. So all

Developers who are involved in wireless networks will get a good opportunity to get a 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 ();

转载请注明原文地址:https://www.9cbs.com/read-41975.html

New Post(0)