最後我們完成MIDlet,在其中包括聯網的程序代碼,由於本站已經提供了很多關於J2ME聯網的介紹,因此這裡不再進行更多的解釋。
package com.J2MEdev.mail;
import Java.io.DataOutputStream;
import Java.io.IOException;import Javax.microedition.midlet.MIDlet;
import Javax.microedition.midlet.MIDletStateChangeException;
import Javax.microedition.lcdui.*;
import Javax.microedition.io.*;public class MailClIEnt extends MIDlet
{
private MainForm mainForm;
private ContentForm contentForm;
private Display display;
private Message message;
public Message getMessage()
{
return message;
}public void setMessage(Message message)
{
this.message = message;
}public void displayAlert(String text, AlertType type, Displayable disp)
{
Alert alert = new Alert("Application Error");
alert.setString(text);
alert.setType(type);
alert.setTimeout(2000);
display.setCurrent(alert, disp);
}
public ContentForm getContentForm()
{
return contentForm;
}public Display getDisplay()
{
return display;
}
public MainForm getMainForm()
{
return mainForm;
}public void initMIDlet()
{
MailThread t = new MailThread(this);
t.start();
message = new Message();
display = Display.getDisplay(this);
mainForm = new MainForm(this, "Simple Mail ClIEnt");
contentForm = new ContentForm("Content", null, 150, TextFIEld.ANY, this);
display.setCurrent(mainForm);
}
protected void startApp() throws MIDletStateChangeException
{
initMIDlet();
}protected void pauseApp()
{
}protected void destroyApp(boolean arg0) throws MIDletStateChangeException
{
}
}class MailThread extends Thread
{
private MailClIEnt midlet;
public MailThread(MailClIEnt midlet)
{
this.midlet = midlet;
}public void run()
{
synchronized(midlet)
{
try
{
midlet.wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("connecting to server.....");
HttpConnection httpConn = null;
DataOutputStream DOS = null;
try
{
httpConn = (HttpConnection)Connector.open("http://localhost:8088/mail/maildo");
httpConn.setRequestMethod("POST");
DOS = new DataOutputStream(httpConn.openOutputStream());
DOS.writeUTF(midlet.getMessage().getTo());
DOS.writeUTF(midlet.getMessage().getSubject());
DOS.writeUTF(midlet.getMessage().getContent());
DOS.close();
httpConn.close();
System.out.println("end of sending mail");
}
catch(IOException e)
{}
}}