Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Hypertext transfer Protocol on Wireless J2ME Devices

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to implement the hypertext transfer protocol on wireless J2ME devices. It is very detailed and has a certain reference value. Interested friends must read it!

As more and more mobile phones and personal digital assistants begin to integrate into the information superhighway, it becomes more and more important to access web sites from mobile devices. Java sets a precedent for small and medium-sized storage capacity in consumer devices and is an ideal language for developing applications for mobile phones, pagers and other micro devices.

In this article, we will learn how to send an HTTP GET request and an HTTP POST request to the server from a j2me client. Although this is only a discussion of the nature of the article, I assume that the reader is already familiar with Java,J2ME and how Java Midlets (MIDP applications) works. We will use J2ME's MIDP profile and use SUN's J2ME's wireless application development kit to compile, configure, and test our application. 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 J2ME client to send HTTP requests to Web servers and similar HTTP-enabled servers? The answer is to use the network class of J2ME that can be found in the javax.microedition.io package. This article wants to elaborate on this issue.

This article provides an overview of ∶

Using J2ME to design wireless network applications

. Send a hypertext GET request

. Send a hypertext POST request

. Using J2ME for Wireless Network programming

The network programming ability of Java 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 strong cpu processing capabilities, fast memory and persistent data storage, but these are not realistic on most wireless devices. Therefore, J2ME defines a subset of these functions and provides a fixed set of packages for network and file access-the javax.microedition.io package. Due to the wide variety of mobile devices, this package defines only one set of interfaces, leaving an actual application interface implementation for each mobile device supplier. This finds the best balance between portability and the application of device-specific features.

The abstract network and file input and output framework defined in the javax.microedition.io class is called the Universal connection Framework (Generic Connection framework, referred to as GCF). GCF defines a set of abstractions to describe different communication methods. The highest abstraction is called Connection, and six interfaces are declared (four are direct and two are indirect). These seven interfaces form part of J2ME's CLDC, which is the configuration used by most wireless devices that can use Java. This configuration is designed to provide common network and file input and output capabilities for all CLDC devices (mobile phones, two-way pagers, low-end PDA, etc.). Although GCF is intended for a common network and file I / O framework, the manufacturer does not require the implementation of all the interfaces declared in GCF. Some manufacturers can decide to support only socket connections, while others can choose to support only Datagram-based communications. To facilitate portability across similar devices, the MIDP specification requires all MIDP devices to implement HttpConnection interfaces. 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 a HTTP GET request

This section will focus on explaining the program code, and in the next section we will only talk about the generic connection framework interface and the HttpConnection interface that are used to send HTTP requests and retrieve responses returned by the server. The program code for creating the MIDP user interface is shown in the appendix.

We first define a method to put the code used to send the HTTP GET request. Because some of the operations in this method have the potential to throw IOException, we will throw such an exception to the calling 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 cast this connection to the desired type, in this case the HttpConnection type.

Hcon = (HttpConnection) Connector.open (url)

Next, we get a DataInputStream on HttpConnection that allows us to read the server's response data character by character.

Dis = new DataInputStream (hcon.openInputStream ())

Using the read () method of DataInputStream, each character of the server response is grouped into a 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 snippet

Return message.toString ()

} / / end sendGetRequest (String)

How to send a HTTP POST request

As you can imagine, the process of sending a HTTP POST request is very similar to sending a GET request. We will modify an existing command, add a small number of new commands, and add an additional object from the generic connection framework and an additional StringBuffer object to send the POST request weight to the server. The remaining commands will remain the same.

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 a HTTP POST request to the server. Add two new variable descriptions at the top of the method. Declare a variable of type DataOutputStream and another variable of type String. 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

The modify connector.open () command contains another parameter that indicates that the connection will allow the client to read and write 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 is GET).

Hcon.setRequestMethod (HttpConnection.POST)

Get a DataOutputStream object for an existing HTTP connection.

Dos = hc.openDataOutputStream ()

Declare a byte array and initialize it by retrieving a byte array from a requestBody string. Then write the buffer of DataOutputStream into the byte array.

Byte [] byteRequest = requestBody.getBytes ()

For (int I = 0; I < byteRequest.length; iTunes +) {

Dos.writeByte (byteRequest [I])

} / / end for (int I = 0; I < byteRequest.length; iTunes +)

Dos.flush (); / / contains this sentence, which may produce unexpected results on some quilts.

The intention of calling the flush () method is to send written data to the buffer of DataOutputStream's server. On some phones, this operation works fine, on others, it causes the Transfer-Encoding of the HTTP request to be set to "chunked", and some random characters are placed before and after the request itself. Then how to deal with this problem? This method call is actually not needed at all. In the next line, the server connection is opened (via openInputStream ()), and the buffer is automatically entered. Therefore, you'd better not call the buffer's flush () method. The rest of this method remains the same, 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! And see the program code attached to this article.

With the increasing popularity of wireless devices that can use the Internet and support the Internet, Java and J2ME are becoming more and more important. Because http is currently the only network protocol supported by all devices that follow the MIDP specification, it is also the best candidate for developing wireless network applications.

In this article, we explored the basic structure and several core issues of wireless network programming, and we looked at how to invoke the two most commonly used HTTP request methods: GET and POST. J2ME is still in its early stages of development, and wireless devices are about to be popularized on a large scale. Therefore, all developers who want to devote themselves to wireless network programming will have a good opportunity to do their best.

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 URL

Private FoRM requestScreen

Private TextField requestField

/ / graphical user interface component used to submit the request

Private List list

Private String [] menuItems

/ / graphical user interface components for displaying server responses

Private Form resultScreen

Private StringItem resultField

/ / "send" button for requestScreen

Command sendCommand

/ / "exit" button for requestScreen

Command exitCommand

/ / "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)

/ / first, the information 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)

NotifyDestroyed ()

} / / 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 using READ permissions

Hcon = (HttpConnection) Connector.open (url)

/ / get 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 and write permissions

Hcon = (HttpConnection) Connector.open (url, Connector.READ_WRITE)

/ / set the request method to POST

Hcon.setRequestMethod (HttpConnection.POST)

/ / get the DataOutputStream that sends the request string

Dos = hcon.openDataOutputStream ()

Byte [] request_body = requeststring.getBytes ()

/ / send request string to server

For (int I = 0; I < request_body.length; iTunes +) {

Dos.writeByte (request_ Body [I])

} / / end for (int I = 0; I < request_body.length; iTunes +)

/ / get the DataInputStream that receives the response from the server

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 input / output streams and HTTP connections

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

The above is all the contents of the article "how to implement Hypertext transfer Protocol on Wireless J2ME Devices". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report