⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpdemo.java

📁 j2me学习 简单例子
💻 JAVA
字号:
package example.demowireless.http;

import java.io.IOException;
import java.io.InputStream;

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.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * <p>J2ME HttpDemo Show Safety Model</p>
 * 
 * @author 刘光辉
 * @version 2009.02.04
 */
public class HttpDemo extends MIDlet implements CommandListener, Runnable {

	private static final Command CMD_EXIT = new Command("Exit",Command.EXIT,1);
	private static final Command CMD_OK = new Command("Ok",Command.OK,1);
	private final TextField text = new TextField("","http://www.baidu.com",256,TextField.ANY);
	private final Form form = new Form("Http Result");
	
	/**
	 * <p>HttpDemo的构造函数</p>
	 */
	public HttpDemo() {

	}

	/**
	 * <p>启动程序,使MIDlet处于active状态</p>
	 * <p></p>
	 * @see javax.microedition.midlet.MIDlet#startApp()
	 */
	protected void startApp() throws MIDletStateChangeException {
		if(Display.getDisplay(this).getCurrent() == null){
			form.append(text);
			form.addCommand(CMD_EXIT);
			form.addCommand(CMD_OK);
			form.setCommandListener(this);
			Display.getDisplay(this).setCurrent(form);
		}
	}

	public void run() {
		//do an action that requires permission, e.g. HTTP connection
		//MIDlet 会读取指定的url 并把字节数显示在文本框
		try{
			String url = text.getString();
			HttpConnection httpConn = (HttpConnection) Connector.open(url);
			InputStream is = httpConn.openInputStream();
			int counter = 0;
			int ch ;
			while((ch = is.read()) != -1){
				counter++;
			}
			is.close();
			httpConn.close();
			text.setString("Bytes read:"+counter);
			
		}catch(IOException e){
			text.setString("IOException: " + e.getMessage());
		}catch(SecurityException e){
			text.setString("SecurityException: " + e.getMessage());
		}
	}
	
	/**
	 * <p>暂停程序,使MIDlet处于pause状态</p>
	 * @see javax.microedition.midlet.MIDlet#pauseApp()
	 */
	protected void pauseApp() {

	}

	/**
	 * <p>销毁程序,使MIDlet处于destroyed状态</p>
	 * 
	 * @param boolean unconditional 
	 * <ul>true 释放资源保存数据进入destroyed状态,false 抛出异常保持当前状态</ul>
	 * @see javax.microedition.midlet.MIDlet#destroyApp(boolean)
	 */
	protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {

	}

	/**
	 * <p>命令处理函数,实现CommandListener接口</p>
	 * @param Command c 命令对象
	 * @param Displayable d 被放置到显示屏显示的对象
	 */
	public void commandAction(Command c, Displayable d) {
		if(c == CMD_EXIT){
			notifyDestroyed();
		}else if(c == CMD_OK){
			new Thread(this).start();
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -