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 until requested rc = c.getResponseCode (); if (rc = HttpConnection.HTTP_OK!) {throw new IOException ( "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 action = 0; int BytesRead = 0; Byte [] data = new byte [len]; while ((bytesread! = len) && (actual! = -1)) {actual = is.read (data, bytesread, le - bytesread); BytesRead = actual;} process (data);} else {Int Ch; While ((ch = is.read ())! = -1) {process ((byte) ch);}}} catch (classcastexception e) {throw new IllegalGumeTexception ("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 (it is recommended to read the API DOC). 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 until requested rc = c.getResponseCode (); if (rc = HttpConnection.HTTP_OK!) {throw new IOException ( "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 action = 0; int BytesRead = 0; Byte [] data = new byte [len]; while ((bytesread! = len) && (actual! = -1)) {actual = is.read (data, bytesread, le - bytesread); BytesRead = actual;} process (data);} else {Int Ch; While ((ch = is.read ())! = -1) {process ((byte) ch);}}} catch (classcastexception e) {throw new IllegalGumeTexception ("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 (it is recommended to read the API DOC). 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 until requested rc = c.getResponseCode (); if (rc = HttpConnection.HTTP_OK!) {throw new IOException ( "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 action = 0; int BytesRead = 0; Byte [] data = new byte [len]; while ((bytesread! = len) && (actual! = -1)) {actual = is.read (data, bytesread, le - bytesread); BytesRead = actual;} process (data);} else {Int Ch; While ((ch = is.read ())! = -1) {process ((byte) ch);}}} catch (classcastexception e) {throw new IllegalGumeTexception ("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 (it is recommended to read the API DOC). The following is based on your own experience: We should understand how this works, the phone sends request to the operator's WAP gateway through the wireless network, the WAP gateway forwards the request to the web server, the server can use CGI , ASP, Servlet / JSP, etc. 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. Consider 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 (); // Todo Method Stub generated by Lomboz} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response); // TODO Method stub generated by Lomboz}} networked time must be 1 in the following process, to establish a connection, Setting the transmission method recommended POST, set the method head 2, open the output stream, transmit data to server 3, determine the corresponding state code, enter different flow control, pay attention to error processing. If OK starts accepting data 4, turn off the connection and flow is the client's code, and 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 MET hod 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 UIController {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 CONNECT_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;} default: 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 (); uiicontroller.handleevent (UiController.EventID.c) ONNECT_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 the 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 (); input = this.openDataInputStream (httpConn); result = input.readUTF (); closeConnection (httpConn, input, output); return result;} 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 ioe) { throw ioe;}} private DataInputStream openDataInputStream (HttpConnection conn) throws IOException {int code = conn.getResponseCode (); if (code == HttpConnection.HTTP_OK) {return conn.openDataInputStream ();} else {throw new IOException (); }} private DataOutputStream OpenDataOutputStream (httpconnection conn) throws oExcepti on {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;