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

📄 cookietest.java

📁 java手机程序开发随书光盘源代码
💻 JAVA
字号:
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;

public class CookieTest extends MIDlet implements CommandListener, Runnable{

	Display display;
	RecordStore cookieStore;
	Command exitCmd;
	Command connectCmd;
	TextBox inputURL;
	Alert alert;
	String defaultURL = "http://127.0.0.1:8080/servlet/CookieGenServlet";
	Thread connectThread;

	public CookieTest(){
		display = Display.getDisplay(this);
		inputURL = new TextBox("输入URL", defaultURL, 100, TextField.URL);
		try{
			cookieStore = RecordStore.openRecordStore("cookie", true);
		}
		catch(Exception ex){}
		alert = new Alert("回应信息");
		alert.setTimeout(Alert.FOREVER);
		connectThread = new Thread(this);
		exitCmd = new Command("退出", Command.EXIT, 1);
		connectCmd = new Command("联机", Command.SCREEN, 1);
		inputURL.addCommand(exitCmd);
		inputURL.addCommand(connectCmd);
		inputURL.setCommandListener(this);
	}

	public void startApp(){
		display.setCurrent(inputURL);
	}

	public void pauseApp(){
	}

	public void destroyApp(boolean conditional){
		try{
			cookieStore.closeRecordStore();
		}
		catch(Exception ex){}
	}

	public void commandAction(Command c, Displayable d){
		if( c == exitCmd){
			destroyApp(true);
			notifyDestroyed();
		}
		else if (c == connectCmd){
			try{
				connectThread.start();
			}
			catch(Exception ex){}
		}
	}

	public void run(){
		String url = inputURL.getString();
		try{
			connect(url);
			display.setCurrent(alert, inputURL);
		}
		catch(Exception ex){}
	}

	void connect(String url) throws IOException{


		HttpConnection con = (HttpConnection)Connector.open(url);
		con.setRequestMethod(HttpConnection.GET);
		byte[] cookie = new byte[10];

		try{
			if(cookieStore.getNumRecords()>0){
				if(cookieStore.getRecordSize(1)>cookie.length)
					cookie = new byte[cookieStore.getRecordSize(1)];
				cookieStore.getRecord(1, cookie, 0);
				con.setRequestProperty("cookie", new String(cookie));
			}
		}
		catch(Exception ex){}

		InputStream ins = con.openInputStream();

		if(con.getResponseCode() == HttpConnection.HTTP_OK){
			try{
				if(cookieStore.getNumRecords() == 0){
					String newCookie = con.getHeaderField("set-cookie");
					byte[] cookieData = newCookie.getBytes();
					cookieStore.addRecord(cookieData, 0, cookieData.length);
				}
			}
			catch(Exception ex){}
		}

		try{
			int length = (int)con.getLength();
			byte[] data = new byte[length];
			ins.read(data);
			String response = new String(data);
			alert.setString(response);
		}
		finally{
			if(ins != null)
				ins.close();
			if(con != null)
				con.close();
		}
	}

}

⌨️ 快捷键说明

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