import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class HttpMIDlet extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command sendCommand = new Command("Send", Command.OK, 1);
private Command backCommand = new Command("Upload", Command.OK, 1);
private Display display;
private String URL = "http://localhost/Java.png";
private Form mainForm, resultForm;
private Item mItem;
private TextField URLField = new TextField(null, URL, 250, TextField.URL);
public HttpMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
mainForm = new Form("Address");
mainForm.append(URLField);
mainForm.addCommand(sendCommand);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
display.setCurrent(mainForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == sendCommand) {
resultForm = new Form("Image");
String URLString = URLField.getString();
try {
Image image = loadImage(URLString);
mItem = new ImageItem(null, image, 0, null);
} catch (IOException ioe) {
mItem = new StringItem(null, ioe.toString());
}
resultForm.append(mItem);
resultForm.addCommand(backCommand);
resultForm.setCommandListener(this);
display.setCurrent(resultForm);
} else if (c == backCommand) {
URLField.setString(URL);
display.setCurrent(mainForm);
} else {
destroyApp(false);
notifyDestroyed();
}
}
public Image loadImage(String url) throws IOException {
HttpConnection hpc = null;
DataInputStream dis = null;
try {
hpc = (HttpConnection) Connector.open(url);
int length = (int) hpc.getLength();
byte[] data = new byte[length];
dis = new DataInputStream(hpc.openInputStream());
dis.readFully(data);
return Image.createImage(data, 0, data.length);
} finally {
if (hpc != null)
hpc.close();
if (dis != null)
dis.close();
}
}
}
|