Use example to illustrate the use of J2ME universal networked framework

zhaozj2021-02-12  129

Although the current wireless network is not ideal, the mobile phone network is not shocked by our developers. After all, this is really a magical thing, isn't it? This article describes how to apply the Universal Networking Framework for the J2ME platform to develop a networking application.

First, you must explain that: MIDP is specified, any mobile information device must provide support from the HTTP protocol, and like other communication methods such as Sockets are devices. Some mobile phones will be supported, some do not support. Here only explains the content related to the HTTP protocol, if you don't understand this knowledge, please refer to the HTTP protocol. In javax.microedition.IO is a large number of interfaces, only one Connector class, of course, add support for Push technology in MIDP2.0, this stay later. The most important way to provide for the CONNECTOR class is the Open () method. Its return value is Connection, you can convert him to the type you need, such as accessing the server with an HTTP protocol.

void postViaHttpConnection (String url) throws IOException {HttpConnection c = null; InputStream is = null; OutputStream os = null; int rc; try {c = (HttpConnection) Connector.open (url); // Set the request method and headers c .SetRequestMethod (httpConnection.post); C.SetRequestProperty ("if-modified-since", "29 OCT 1999 19:43:31 GMT"); C.SetRequestProperty ("User-Agent", "Profile / MIDP-2.0 Configuration /Cldc-1.0 "); C.SetRequestProperty (" Content-Language "," EN-US "); // getting the output stream may flush the headers OS = C.OpenOutputStream (); os.write (" List games / N ".getbytes (); Os.Flush (); // Optional, GetResponsecode Will Flush // Getting The Response Code Will Open The Connection, // Send The Request, And Read The http response headers. // The Headers Are Stored untric Requ Ested. rc = c.getResponsecode (); if (rc! = httpconnection.htttp_ok) {throw new oException ("http response code: rc);} is = c.openInputStream (); // Get the contenttype string TYPE = c.gettype (); processtype (type); // Get the length and process the data int LEN = (int) c.getlength (); if (len> 0) {int actual = 0; int bittesread = 0; Byte [] data = new byte [len]; while ((bytesread! = len) && (actual! =

-1)) {actual = is.read (data, bytesread, len - bytesread); BytesRead = actual;} process (data);} else {Int ch; while ((ch = is.read ())! = -1) {process ((byte) ch);}}} catch (classcastexception e) {throw new IllegaLutException ("not an http url");} finally {if (is! = Null) is.close (); if (OS! = null) Os.close (); if (c! = null) c.close ();}} The above code is I taken from the API DOC (I have read more API DOC). Below, according to your own experience, it is important to the net network:

We should understand how this is working, and the mobile phone sends a request to the operator's WAP gateway through the wireless network. The WAP gateway forwards the request to the web server, and the server can build in CGI, ASP, Servlet / JSP. After the server is processed, the response will be forwarded to the WAP gateway, and the WAP gateway will send it to the phone. Wap Gateway is transparent to our developers. We don't have to manage it. If you can't see Thread, runnable in your netbook, then your program cannot run. Since the factors considering the network, in order to avoid operational jamming. You must put the networked action to another thread and cannot run in the main thread. It is best to provide a waiting interface such as an animation interface when it is networked. I am not used in the examples provided below, because I want to talk about this separately. Usually the interface of the networked application is more, it is best to use the MVC mode to implement the navigation of the interface. About this aspect of the instructions I have previously have a story about how you want to pass your data, this is very important. You can use the GET method to use the Post method, the latter can be recommended. Because the GET method can only be transmitted through the URL encoding. And POST is more flexible, with DataInputStream, DataOutputStream to use it easier. We must know how we accept data is related to how data is related, such as Writeutf (Message); WriteBoolean (4); WriteBoolean (TRUE), then accept should be readf (); readint (); ReadBoolean (); If the sending data length is available, we can create an appropriate array to accept, if we do not use us to accept an appropriate capacity array to accept.

Below I provide an example to illustrate the above problems, in the application, we enter any character, and get a response by connecting Server and displayed. Server I wrote very simple, just after the content received, add "Haha", and the program runs without any problems on your mobile phone, that is, the GPRS network is not fast enough. Server is Tomcat5 implementation, and the issue of how to deploy servlet is exceeded in the discussion scope of this article. I only provide code, recommend Eclipse Lomboz to develop J2EE programs. / * * Created on 2004-7-5 * * TODO To change the template for this generated file go to Window - * Preferences - Java - Code Generation - Code and Comments * / package com.north; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; / * * * @author P2800 * * TODO to change the template for this generated type comment go to Window - * Preferences - Java - Code Generation - Code and Comments * / public class MyServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {DataInputStream dis = new DataInputStream (request.getInputStream ()); String result = dis.readUTF (); DataOutputStream dos = new DataOutputStream (response.getOutputStream ()); dos.writeUTF (result "haha"); DOS.Close (); dis.close (); // Tod O Method stub generated by Lomboz} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response); // TODO Method stub generated by Lomboz}} FIG originally wanted posted but can not Upload success, try it tomorrow! When the network is connected, it must be established according to the following process. Set the transmission method to recommend POST, set the method head to open the output stream, transfer the data to the server to determine the corresponding status code, enter different process control, pay attention Error handling. If OK starts accepting data to close the connection and flow is the code of the client, there is no consideration for the error handling. A total of 5 classes

import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; / * * Created on 2004-7-4 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates * // ** * @author P2800 * * TODO to change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates * / public class HttpCommMIDlet extends MIDlet {

private UIController uicontroller; / * (non-Javadoc) * @see javax.microedition.midlet.MIDlet # startApp () * / protected void startApp () throws MIDletStateChangeException {// TODO Auto-generated method stub uicontroller = new UIController (this) UiController.init ();

}

/ * (non-javadoc) * @see javax.microedition.midlet.midlet # Pauseapp () * / protected void Pauseapp () {// Todo auto-generated method stub

}

/ * (Non-Javadoc) * @see javax.microedition.midlet.MIDlet # destroyApp (boolean) * / protected void destroyApp (boolean arg0) throws MIDletStateChangeException {// TODO Auto-generated method stub

}

Import java.io.ioException;

Import javax.microedition.lcdui.display; import javax.microedition.lcdui.displayable;

/ * * Created on 2004-7-4 * * Todo to change the Template for this generated file go to * window - preferences - java - code style - code templates * /

/ ** * @Author p2800 * * Todo to change the template for this generated type comment go to window - * preferences - java - code style - code templates * / public class uilicontroller {

private HttpCommMIDlet midlet; private InputCanvas inputUI; private DisplayCanvas displayUI; private Display display; private HttpCommHandler httpHandler; / ** * * / public UIController (HttpCommMIDlet midlet) {this.midlet = midlet; // TODO Auto-generated constructor stub}

Public static class eventid {public static final int connection_to_server = 0; public static final int display_back_to_input = 1;}

public void init () {display = Display.getDisplay (midlet); httpHandler = new HttpCommHandler ( "http://222.28.218.222:8088/http/myservlet"); inputUI = new InputCanvas (this); displayUI = new DisplayCanvas ( This); Display.SetCurrent (Inputui);

Public void setcurrent (Displayable DISP) {Display.SetCurrent (DISP);

Public void Handleevent (int eventid, object [] obj) {new eventhandler (EventID, obj) .start ();

Private Class EventHandler Extends Thread {Private Int EventId; Private Object [] Obj; Private Displayable Backui;

Public EventHandler (int eventid, object [] obj) {this.eventid = EventId; this.obj = obj;}

Public void Run () {synchronized (this) {run (eventid, obj);}}

Private void Run (int eventid, object [] obj) {switch (eventid) {copy eventid.connect_to_server: {TRY {

String result = httpHandler .sendMessage ((String) obj [0]); displayUI.init (result); setCurrent (displayUI); break;} catch (IOException e) {}} case EventID.DISPLAY_BACK_TO_INPUT: {setCurrent (inputUI); Break;}}};

import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.StringItem; import javax.microedition. LCDUI.TEXTFIELD;

/ * * Created on 2004-7-4 * * Todo to change the Template for this generated file go to * window - preferences - java - code style - code templates * /

/ ** * @author P2800 * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates * / public class InputCanvas extends Form implements CommandListener {private UIController uicontroller; private TextField inputField PRIVATE STRINGITEM RESULT; Public Static Final Command Okcommand = New Command ("OK", Command.ok, 1);

public InputCanvas (UIController uicontroller) {super ( "Http Comunication"); this.uicontroller = uicontroller; inputField = new TextField ( "Input:", null, 20, TextField.ANY); this.append (inputField); this.addCommand (okcommand); this.setcommandlistener (this);}

/ * * (Non-Javadoc) * * @see javax.microedition.lcdui.CommandListener # commandAction (javax.microedition.lcdui.Command, * javax.microedition.lcdui.Displayable) * / public void commandAction (Command arg0, Displayable arg1 ) {// TODO Auto-generated method stub if (arg0 == okCommand) {String input = inputField.getString (); uicontroller.handleEvent (UIController.EventID.CONNECT_TO_SERVER, new Object [] {input});}}

}

Import java.io. *;

Import javax.microedition.io.connector; import javax.microedition.io.httpConnection;

/ * * Created on 2004-7-4 * * Todo to change the Template for this generated file go to * window - preferences - java - code style - code templates * /

/ ** * @Author p2800 * * Todo to change TEMPLATE for this generated Type Comment Go to window - * preferences - java - code style - code templates * / public class httpcommhandler {private string URL;

Public httpcommhandler (string URL) {this.url = url;}

public String sendMessage (String message) throws IOException {HttpConnection httpConn; DataInputStream input; DataOutputStream output; String result; try {httpConn = open (); output = this.openDataOutputStream (httpConn); output.writeUTF (message); output.close ( ); Infut = this.opendataInputStream (httpconn); result = INPUT.Readutf (); CloseConnection (httpconn, input, output); returnrate;

}

Finally {

}

}

public HttpConnection open () throws IOException {try {HttpConnection connection = (HttpConnection) Connector.open (URL); connection.setRequestProperty ( "User-Agent", System .getProperty ( "microedition.profiles")); connection.setRequestProperty ( " Content-type "," Application / OcTet-Stream "); connection.setRequestMethod (httpConnection.post);

Return Connection;} catch (ioexception ie) {

Throw IoE;

}

Private DataInputStream OpenDataInputStream (httpConnection Conn) throws oException

{Int code = conn.getResponsecode (); if (code == httpconnection.http_ok) {return ();} else {throw new oException ();}}

Private DataOutputStream OpenDataOutputStream (httpconnection conn) throws oews oException {return conn.opendataoutputstream ();

private void closeConnection (HttpConnection conn, DataInputStream dis, DataOutputStream dos) {if (conn = null!) {try {conn.close ();} catch (IOException e) {}} if (! dis = null) {try {dis .close ();} catch (ioException e) {}}}} (dos! = null) {Try {dos.close ();} catch (ioException e) {}}}

}

import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.StringItem; / * * Created on 2004-7-6 * * Todo to change the template for this generated file go to * window - preferences - java - code style - code templates * /

/ ** * @author P2800 * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates * / public class DisplayCanvas extends Form implements CommandListener {private UIController uicontroller; private StringItem result Private int index = 0; private boolean first = true; public static command backcommand = new Command ("back", command.back, 2);

public DisplayCanvas (UIController uicontroller) {super ( "Result"); this.uicontroller = uicontroller; result = new StringItem ( "you have input:", null); this.addCommand (backCommand); this.setCommandListener (this);

}

Public void init.Settext (message); index = this.Append (result); first = false;} else {this.delete (index); result.settext (Message); this.Append (result);

}

/ * * (Non-Javadoc) * * @see javax.microedition.lcdui.CommandListener # commandAction (javax.microedition.lcdui.Command, * javax.microedition.lcdui.Displayable) * / public void commandAction (Command arg0, Displayable arg1 ) {// Todo auto-generated method stub uiController.handleevent (uiicontroller.eventid.display_back_to_input, null);}

}

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

New Post(0)