Java/J2ME/Networks
Содержание
- 1 An example MIDlet to invoke a CGI script.
- 2 A simple network client
- 3 Cookie MIDlet
- 4 Datagram Receiver
- 5 DatagramSender
- 6 Demonstrates the functionality of DatagramConnection framework.
- 7 Fetch Page Midlet
- 8 Get file from network
- 9 Http Connection
- 10 Http Example
- 11 Http MIDlet
- 12 Https MIDlet
- 13 Http Test
- 14 Invoke Servlet Midlet 1
- 15 Invoke Servlet Midlet 2
- 16 Jargoneer
- 17 Midlet Servlet 2
- 18 MIDlet to fetch a page using an HttpConnection
- 19 MIDlet to invoke a CGI script.
- 20 MIDlet to invoke a CGI script (GET method).
- 21 MIDlet to invoke a CGI script (POST method is used)
- 22 MIDlet to invoke a CGI script (POST method is used) (2)
- 23 Pass a cookie (stored in rms) between the MIDlet and a Java servlet.
- 24 Patchy MIDlet
- 25 Post MIDlet
- 26 Sample to demonstrate Http GET and POST from MIDlet
- 27 Send client request and Get server response
- 28 Socket connection
- 29 Socket MIDlet
- 30 Timer Server
- 31 Time Server
- 32 Use GET or POST to communicate with a Java servlet.
- 33 Use Java servlets sessions to tally golf scores.
- 34 www.amazon.com Book Ranking MIDlet
An example MIDlet to invoke a CGI script.
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a CGI script.
*/
public class ThirdExample extends MIDlet {
private Display display;
String url = "http://www.javacourses.ru/cgi-bin/getgrade.cgi?idnum=182016";
public ThirdExample() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
getGrade(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Retrieve a grade....
*/
void getGrade(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
int x = 5, y =7;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("IF-Modified-Since", "10 Nov 2000 17:29:12 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
/*
String str = "?idnum=182016";
byte postmsg[] = str.getBytes();
for(int i=0;i<postmsg.length;i++) {
os.writeByte(postmsg[i]);
}
os.flush();
*/
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.println((char)ch);
}
t = new TextBox("Final Grades", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
A simple network client
/*
* Copyright (c) 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
*/
import java.lang.*;
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* A simple network client.
*
* This MIDlet shows a simple use of the HTTP
* networking interface. It opens a HTTP POST
* connection to a server, authenticates using
* HTTP Basic Authentication and writes a string
* to the connection. It then reads the
* connection and displays the results.
*/
public class NetClientMIDlet extends MIDlet
implements CommandListener {
private Display display; // handle to the display
private Form mainScr; // main screen
private Command cmdOK; // OK command
private Command cmdExit; // EXIT command
private Form dataScr; // for display of results
/**
* Constructor.
*
* Create main screen and commands. Main
* screen shows simple instructions.
*/
public NetClientMIDlet() {
display = Display.getDisplay(this);
mainScr = new Form("NetClient");
mainScr.append("Hit OK to make network connection");
mainScr.append(" ");
mainScr.append("Hit EXIT to quit");
cmdOK = new Command("OK", Command.OK, 1);
cmdExit = new Command("Exit", Command.EXIT, 1);
mainScr.addCommand(cmdOK);
mainScr.addCommand(cmdExit);
mainScr.setCommandListener(this);
}
/**
* Called by the system to start our MIDlet.
* Set main screen to be displayed.
*/
protected void startApp() {
display.setCurrent(mainScr);
}
/**
* Called by the system to pause our MIDlet.
* No actions required by our MIDLet.
*/
protected void pauseApp() {}
/**
* Called by the system to end our MIDlet.
* No actions required by our MIDLet.
*/
protected void destroyApp(boolean unconditional) {}
/**
* Gets data from server.
*
* Open a connection to the server, set a
* user and password to use, send data, then
* read the data from the server.
*/
private void genDataScr() {
ConnectionManager h = new ConnectionManager();
// Set message to send, user, password
h.setMsg("Esse quam videri");
h.setUser("book");
h.setPassword("bkpasswd");
byte[] data = h.Process();
// create data screen
dataScr = new Form("Data Screen");
dataScr.addCommand(cmdOK);
dataScr.addCommand(cmdExit);
dataScr.setCommandListener(this);
if (data == null || data.length == 0) {
// tell user no data was returned
dataScr.append("No Data Returned!");
} else {
// loop trough data and extract strings
// (delimited by "\n" characters
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
if (data[i] == (byte)"\n") {
dataScr.append(sb.toString());
sb.setLength(0);
} else {
sb.append((char)data[i]);
}
}
}
display.setCurrent(dataScr);
}
/**
* This method implements a state machine that drives
* the MIDlet from one state (screen) to the next.
*/
public void commandAction(Command c,
Displayable d) {
if (c == cmdOK) {
if (d == mainScr) {
genDataScr();
} else {
display.setCurrent(mainScr);
}
} else if (c == cmdExit) {
destroyApp(false);
notifyDestroyed();
}
}
}
/*
* Copyright (c) 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
*/
/**
* This class encodes a user name and password
* in the format (base 64) that HTTP Basic
* Authorization requires.
*/
class BasicAuth {
// make sure no one can instantiate this class
private BasicAuth() {}
// conversion table
private static byte[] cvtTable = {
(byte)"A", (byte)"B", (byte)"C", (byte)"D", (byte)"E",
(byte)"F", (byte)"G", (byte)"H", (byte)"I", (byte)"J",
(byte)"K", (byte)"L", (byte)"M", (byte)"N", (byte)"O",
(byte)"P", (byte)"Q", (byte)"R", (byte)"S", (byte)"T",
(byte)"U", (byte)"V", (byte)"W", (byte)"X", (byte)"Y",
(byte)"Z",
(byte)"a", (byte)"b", (byte)"c", (byte)"d", (byte)"e",
(byte)"f", (byte)"g", (byte)"h", (byte)"i", (byte)"j",
(byte)"k", (byte)"l", (byte)"m", (byte)"n", (byte)"o",
(byte)"p", (byte)"q", (byte)"r", (byte)"s", (byte)"t",
(byte)"u", (byte)"v", (byte)"w", (byte)"x", (byte)"y",
(byte)"z",
(byte)"0", (byte)"1", (byte)"2", (byte)"3", (byte)"4",
(byte)"5", (byte)"6", (byte)"7", (byte)"8", (byte)"9",
(byte)"+", (byte)"/"
};
/**
* Encode a name/password pair appropriate to
* use in an HTTP header for Basic Authentication.
* name the user"s name
* passwd the user"s password
* returns String the base64 encoded name:password
*/
static String encode(String name,
String passwd) {
byte input[] = (name + ":" + passwd).getBytes();
byte[] output = new byte[((input.length / 3) + 1) * 4];
int ridx = 0;
int chunk = 0;
/**
* Loop through input with 3-byte stride. For
* each "chunk" of 3-bytes, create a 24-bit
* value, then extract four 6-bit indices.
* Use these indices to extract the base-64
* encoding for this 6-bit "character"
*/
for (int i = 0; i < input.length; i += 3) {
int left = input.length - i;
// have at least three bytes of data left
if (left > 2) {
chunk = (input[i] << 16)|
(input[i + 1] << 8) |
input[i + 2];
output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
output[ridx++] = cvtTable[(chunk&0xFC0) >> 6];
output[ridx++] = cvtTable[(chunk&0x3F)];
} else if (left == 2) {
// down to 2 bytes. pad with 1 "="
chunk = (input[i] << 16) |
(input[i + 1] << 8);
output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
output[ridx++] = cvtTable[(chunk&0xFC0) >> 6];
output[ridx++] = "=";
} else {
// down to 1 byte. pad with 2 "="
chunk = input[i] << 16;
output[ridx++] = cvtTable[(chunk&0xFC0000)>>18];
output[ridx++] = cvtTable[(chunk&0x3F000) >>12];
output[ridx++] = "=";
output[ridx++] = "=";
}
}
return new String(output);
}
}
/*
* Copyright (c) 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
*/
/**
* Manages network connection.
*
* This class established an HTTP POST connection
* to a server defined by baseurl.
* It sets the following HTTP headers:
* User-Agent: to CLDC and MIDP version strings
* Accept-Language: to microedition.locale or
* to "en-US" if that is null
* Content-Length: to the length of msg
* Content-Type: to text/plain
* Authorization: to "Basic" + the base 64 encoding of
* user:password
*/
class ConnectionManager {
private HttpConnection con;
private InputStream is;
private OutputStream os;
private String ua;
private final String baseurl =
"http://127.0.0.1:8080/Book/netserver";
private String msg;
private String user;
private String password;
/**
* Set the message to send to the server
*/
void setMsg(String s) {
msg = s;
}
/**
* Set the user name to use to authenticate to server
*/
void setUser(String s) {
user = s;
}
/**
* Set the password to use to authenticate to server
*/
void setPassword(String s) {
password = s;
}
/**
* Open a connection to the server
*/
private void open() throws IOException {
int status = -1;
String url = baseurl;
String auth = null;
is = null;
os = null;
con = null;
// Loop until we get a connection (in case of redirects)
while (con == null) {
con = (HttpConnection)Connector.open(url);
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty("User-Agent", ua);
String locale =
System.getProperty("microedition.locale");
if (locale == null) {
locale = "en-US";
}
con.setRequestProperty("Accept-Language", locale);
con.setRequestProperty("Content-Length",
"" + msg.length());
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("Accept", "text/plain");
if (user != null && password != null) {
con.setRequestProperty("Authorization",
"Basic " +
BasicAuth.encode(user,
password));
}
// Open connection and write message
os = con.openOutputStream();
os.write(msg.getBytes());
os.close();
os = null;
// check status code
status = con.getResponseCode();
switch (status) {
case HttpConnection.HTTP_OK:
// Success!
break;
case HttpConnection.HTTP_TEMP_REDIRECT:
case HttpConnection.HTTP_MOVED_TEMP:
case HttpConnection.HTTP_MOVED_PERM:
// Redirect: get the new location
url = con.getHeaderField("location");
os.close();
os = null;
con.close();
con = null;
break;
default:
// Error: throw exception
os.close();
con.close();
throw new IOException("Response status not OK:"+
status);
}
}
is = con.openInputStream();
}
/**
* Constructor
* Set up HTTP User-Agent header string to be the
* CLDC and MIDP version.
*/
ConnectionManager() {
ua = "Profile/" +
System.getProperty("microedition.profiles") +
" Configuration/" +
System.getProperty("microedition.configuration");
}
/**
* Process an HTTP connection request
*/
byte[] Process() {
byte[] data = null;
try {
open();
int n = (int)con.getLength();
if (n != 0) {
data = new byte[n];
int actual = is.read(data);
}
} catch (IOException ioe) {
} finally {
try {
if (con != null) {
con.close();
}
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {}
return data;
}
}
}
Cookie MIDlet
/*
Wireless Java 2nd edition
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class CookieMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
private String mSession;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mForm == null) {
mForm = new Form("CookieMIDlet");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.addCommand(new Command("Send", Command.SCREEN, 0));
mForm.setCommandListener(this);
}
mDisplay.setCurrent(mForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) notifyDestroyed();
else {
Form waitForm = new Form("Connecting...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread(this);
t.start();
}
}
public void run() {
String url = getAppProperty("CookieMIDlet-URL");
try {
// Query the server and retrieve the response.
HttpConnection hc = (HttpConnection)Connector.open(url);
if (mSession != null)
hc.setRequestProperty("cookie", mSession);
InputStream in = hc.openInputStream();
String cookie = hc.getHeaderField("Set-cookie");
if (cookie != null) {
int semicolon = cookie.indexOf(";");
mSession = cookie.substring(0, semicolon);
}
int length = (int)hc.getLength();
byte[] raw = new byte[length];
in.read(raw);
String s = new String(raw);
Alert a = new Alert("Response", s, null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mForm);
in.close();
hc.close();
}
catch (IOException ioe) {
Alert a = new Alert("Exception", ioe.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mForm);
}
}
}
Datagram Receiver
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
public class DatagramReceiver {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: DatagramReceiver port");
System.exit(1);
}
try {
DatagramConnection receiver =
(DatagramConnection)Connector.open("datagram://:" + args[0]);
byte[] buffer = new byte[256];
Datagram dgram = receiver.newDatagram(buffer, buffer.length);
for (;;) {
dgram.setLength(buffer.length);
receiver.receive(dgram);
int length = dgram.getLength();
System.out.println("Datagram received. Length is " + length);
// Show the content of the datagram.
for (int i = 0; i < length; i++) {
System.out.print(buffer[i] + " ");
}
System.out.println();
// Send it back...
receiver.send(dgram);
}
} catch (IOException ex) {
System.out.println("IOException: " + ex);
}
}
}
DatagramSender
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
public class DatagramSender {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: DatagramSender port length");
System.exit(1);
}
try {
DatagramConnection sender =
(DatagramConnection)Connector.open("datagram://localhost:" + args[0]);
int length = Integer.parseInt(args[1]);
byte[] buffer = new byte[length];
for (int i = 0; i < length; i++) {
buffer[i] = (byte)("0" + (i % 10));
}
Datagram dgram = sender.newDatagram(buffer, buffer.length);
sender.send(dgram);
// Wait for the packet to be returned
for (int i = 0; i < length; i++) {
buffer[i] = (byte)0;
}
sender.receive(dgram);
length = dgram.getLength();
System.out.println("Received return packet, length is " + length);
// Show the content of the datagram.
for (int i = 0; i < length; i++) {
System.out.print(buffer[i] + " ");
}
System.out.println();
} catch (IOException ex) {
System.out.println("IOException: " + ex);
}
}
}
Demonstrates the functionality of DatagramConnection framework.
/*** Chapter 5 Sample Code for Datagram functionality ***/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.util.*;
public class DatagramTest extends MIDlet {
// Port 9001 is used for datagram communication
static final int receiveport = 9001;
Receive receiveThread = new Receive();
public DatagramTest() {
}
public void startApp() {
// Start the listening thread
receiveThread.start();
// Send message Hello World!
sendMessage("Hello World!");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
// This function sends a datagram message on port 9001.
void sendMessage(String msg) {
String destAddr = "datagram://localhost:" + receiveport;
DatagramConnection dc = null;
Datagram dgram;
byte[] bMsg = msg.getBytes();
try {
dc = (DatagramConnection)Connector.open(destAddr);
// Create a datagram socket and send
dgram= dc.newDatagram(bMsg,bMsg.length,destAddr);
dc.send(dgram);
System.out.println("Sending Packet:" + msg);
dc.close();
}
catch (Exception e) {
System.out.println("Exception Connecting: " + e.getMessage());
}
finally {
if (dc != null) {
try {
dc.close();
}
catch (Exception e) {
System.out.println("Exception Closing: " + e.getMessage());
}
}
}
}
// This function is a listener. It waits to receive datagram packets on 9001 port
class Receive extends Thread {
public void run() {
doReceive();
}
void doReceive() {
DatagramConnection dc = null;
Datagram dgram;
try {
// Open Server side datagram connection
dc = (DatagramConnection)Connector.open("datagram://:"+receiveport);
String receivedMsg;
while (true) {
dgram = dc.newDatagram(dc.getMaximumLength());
try {
dc.receive(dgram);
} catch (Exception e) {
System.out.println("Exception in receiving message:" + e.getMessage());
}
receivedMsg = new String(dgram.getData(), 0,dgram.getLength());
System.out.println("Received Message: " + receivedMsg);
try {
Thread.sleep(500);
}
catch (Exception e) {
System.out.println("Exception doReceive(): " + e.getMessage());
}
}
}
catch (Exception e) {
System.out.println("Exception doReceive(): " + e.getMessage());
}
finally {
if (dc != null) {
try {
dc.close();
}
catch (Exception e) {
System.out.println("Exception Closing: " + e.getMessage());
}
}
}
}
}
}
Fetch Page Midlet
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class FetchPageMidlet extends MIDlet {
private Display display;
String url = "http://www.javacourses.ru/hello.txt";
public FetchPageMidlet() {
display = Display.getDisplay(this);
}
/**
* This will be invoked when we start the MIDlet
*/
public void startApp() {
try {
getViaStreamConnection(url);
} catch (IOException e) {
//Handle Exceptions any other way you like.
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* read url via stream connection
*/
void getViaStreamConnection(String url) throws IOException {
StreamConnection c = null;
InputStream s = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (StreamConnection)Connector.open(url);
s = c.openInputStream();
int ch;
while((ch = s.read()) != -1) {
b.append((char) ch);
}
System.out.println(b.toString());
t = new TextBox("Fetch Page", b.toString(), 1024, 0);
} finally {
if(s != null) {
s.close();
}
if(c != null) {
c.close();
}
}
// display the contents of the file in a text box.
display.setCurrent(t);
}
}
Get file from network
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class FirstExample extends MIDlet {
private Display display;
String url = "http://www.javacourses.ru/hello.txt";
public FirstExample() {
display = Display.getDisplay(this);
}
/**
* This will be invoked when we start the MIDlet
*/
public void startApp() {
try {
getViaStreamConnection(url);
} catch (IOException e) {
//Handle Exceptions any other way you like.
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* read url via stream connection
*/
void getViaStreamConnection(String url) throws IOException {
StreamConnection c = null;
InputStream s = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (StreamConnection)Connector.open(url);
s = c.openInputStream();
int ch;
while((ch = s.read()) != -1) {
b.append((char) ch);
}
System.out.println(b.toString());
t = new TextBox("hello....", b.toString(), 1024, 0);
} finally {
if(s != null) {
s.close();
}
if(c != null) {
c.close();
}
}
// display the contents of the file in a text box.
display.setCurrent(t);
}
}
Http Connection
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: httpconnection
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: httpconnection.jar
MIDlet-1: httpconnection, , httpconnection
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class httpconnection extends MIDlet implements CommandListener {
private Command exit, start;
private Display display;
private Form form;
public httpconnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Http Connection");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
destroyApp(false);
notifyDestroyed();
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
HttpConnection connection = null;
InputStream inputstream = null;
try
{
connection = (HttpConnection) Connector.open("http://www.myserver.ru/myinfo.txt");
//HTTP Request
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("Content-Type","//text plain");
connection.setRequestProperty("Connection", "close");
// HTTP Response
System.out.println("Status Line Code: " + connection.getResponseCode());
System.out.println("Status Line Message: " + connection.getResponseMessage());
if (connection.getResponseCode() == HttpConnection.HTTP_OK)
{
System.out.println(
connection.getHeaderField(0)+ " " + connection.getHeaderFieldKey(0));
System.out.println(
"Header Field Date: " + connection.getHeaderField("date"));
String str;
inputstream = connection.openInputStream();
int length = (int) connection.getLength();
if (length != -1)
{
byte incomingData[] = new byte[length];
inputstream.read(incomingData);
str = new String(incomingData);
}
else
{
ByteArrayOutputStream bytestream =
new ByteArrayOutputStream();
int ch;
while ((ch = inputstream.read()) != -1)
{
bytestream.write(ch);
}
str = new String(bytestream.toByteArray());
bytestream.close();
}
System.out.println(str);
}
}
catch(IOException error)
{
System.out.println("Caught IOException: " + error.toString());
}
finally
{
if (inputstream!= null)
{
try
{
inputstream.close();
}
catch( Exception error)
{
/*log error*/
}
}
if (connection != null)
{
try
{
connection.close();
}
catch( Exception error)
{
/*log error*/
}
}
}
}
}
}
Http Example
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: httpexample
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: httpexample.jar
MIDlet-1: httpexample, , httpexample
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
import java.util.*;
public class HttpExample extends MIDlet implements CommandListener
{
private Command exit, start;
private Display display;
private Form form;
private StringItem stars;
public HttpExample ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Customer Ranking");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
StreamConnection connection = null;
InputStream in = null;
StringBuffer buffer = new StringBuffer();
try
{
connection = (StreamConnection)
Connector.open(
"http://www.amazon.ru/exec/obidos/tg/detail/-/007222472X");
in = connection.openInputStream();
int ch;
while ((ch = in.read()) != -1)
{
if (ch != "\n")
{
buffer.append((char)ch);
}
else
{
String line = new String (buffer.toString());
if(line.equals("out of 5 stars"))
{
int position = line.indexOf("alt=");
Alert alert = new Alert(
"Rating", line.substring(position + 5, position + 8), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
buffer = new StringBuffer();
}
}
}
catch (IOException error)
{
Alert alert = new Alert("Error", "Cannot connect", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
}
}
Http MIDlet
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HttpMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Form addressForm;
private Form connectForm;
private Form displayForm;
private TextField serverURL;
private StringItem messageLabel;
private StringItem errorLabel;
private Command okCommand;
private Command exitCommand;
private Command backCommand;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(addressForm);
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
}
}
public void run() {
InputStream is = null;
HttpConnection conn = null;
try {
String url = serverURL.getString();
if (!url.startsWith("http://") &&
!url.startsWith("https://")) {
url = "http://" + url;
}
conn = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
} catch (Exception ex) {
System.out.println(ex);
ex.printStackTrace();
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
}
try {
// Fetch the required page, reading up
// to a maximum of 128 bytes
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
is = conn.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
} else {
messageLabel.setText("Failed: error " + conn.getResponseCode() +
"\n" + conn.getResponseMessage());
}
// Get the response code and print all the headers
System.out.println("Response code = " + conn.getResponseCode());
System.out.println("Response message = " + conn.getResponseMessage());
for (int i = 0; ; i++) {
String key = conn.getHeaderFieldKey(i);
String value = conn.getHeaderField(i);
if (key == null) {
// Reached last header
break;
}
System.out.println(key + " = " + value);
}
conn.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
System.out.println(ex);
ex.printStackTrace();
Alert alert = new Alert("I/O Error",
"An error occurred while communicating with the server.",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
} finally {
// Close open streams
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException ex1) {
}
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (IOException ex1) {
}
}
}
private void initialize() {
display = Display.getDisplay(this);
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
// The address form
addressForm = new Form("HTTP Client");
serverURL = new TextField("URL:", "", 256, TextField.ANY);
addressForm.append(serverURL);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
// The connect form
connectForm = new Form("Connecting");
messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
// The display form
displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);
}
}
Https MIDlet
/*
Wireless Java 2nd edition
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.pki.*;
public class HttpsMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mForm == null) {
mForm = new Form("HttpsMIDlet");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.addCommand(new Command("Send", Command.SCREEN, 0));
mForm.setCommandListener(this);
}
mDisplay.setCurrent(mForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) notifyDestroyed();
else {
Form waitForm = new Form("Connecting...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread(this);
t.start();
}
}
public void run() {
String url = getAppProperty("HttpsMIDlet-URL");
try {
// Query the server and retrieve the response.
HttpsConnection hc = (HttpsConnection)Connector.open(url);
SecurityInfo si = hc.getSecurityInfo();
Certificate c = si.getServerCertificate();
String subject = c.getSubject();
String s = "Server certificate subject: \n" + subject;
Alert a = new Alert("Result", s, null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mForm);
hc.close();
}
catch (IOException ioe) {
Alert a = new Alert("Exception", ioe.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mForm);
}
}
}
Http Test
/*
* @(#)HttpTest.java 1.14 00/05/24 Copyright (c) 1999,2000 Sun Microsystems,
* Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the terms
* of the license agreement you entered into with Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*/
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
public class HttpTest extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.SCREEN, 2);
private Command reloadCommand = new Command("Reload", Command.SCREEN, 1);
private Command headCommand = new Command("Head", Command.HELP, 1);
private String getUrl = "http://sraju1:8080/hello.txt";
private String headUrl = "http://sraju1:8080/hello.txt?test#home";
private Display display;
public HttpTest() {
display = Display.getDisplay(this);
}
public void startApp() {
// Use the specified URL is overriden in the descriptor
String u = getAppProperty("HttpTest-Url");
if (u != null) {
getUrl = u;
headUrl = u + "?test#home";
}
readPage();
}
private void headPage() {
StringBuffer b = new StringBuffer();
try {
HttpConnection c = null;
c = (HttpConnection) Connector.open(headUrl);
// c.setRequestMethod(request);
c.setRequestMethod(HttpConnection.HEAD);
b.append("URL: " + c.getURL() + "\nProtocol: " + c.getProtocol()
+ "\nHost: " + c.getHost() + "\nFile: " + c.getFile()
+ "\nRef: " + c.getRef() + "\nQuery: " + c.getQuery()
+ "\nPort: " + c.getPort() + "\nMethod: "
+ c.getRequestMethod());
InputStream is = c.openInputStream();
// DEBUG: request System.out.println(b) ;
b.append("\nResponseCode: " + c.getResponseCode()
+ "\nResponseMessage:" + c.getResponseMessage()
+ "\nContentLength: " + c.getLength() + "\nContentType: "
+ c.getType() + "\nContentEncoding: " + c.getEncoding()
+ "\nContentExpiration: " + c.getExpiration() + "\nDate: "
+ c.getDate() + "\nLast-Modified: " + c.getLastModified()
+ "\n\n");
int h = 0;
while (true) {
try {
String key = c.getHeaderFieldKey(h);
if (key == null)
break;
String value = c.getHeaderField(h);
b.append(key + ": " + value + "\n");
h++;
System.out.println(key + "(" + h + "): " + value);
} catch (Exception e) {
System.out.println("Exception while fetching headers");
break;
}
}
try {
is.close();
c.close();
} catch (Exception ce) {
System.out.println("Error closing connection");
}
TextBox t = new TextBox("Http Test", b.toString(), 1024, 0);
System.out.println("String read from URL: " + getUrl + " - is: "
+ b.toString());
t.addCommand(reloadCommand);
t.addCommand(exitCommand);
t.setCommandListener(this);
display.setCurrent(t);
} catch (IOException ex) {
System.out.println("Exception reading from http:" + ex);
}
}
private void readPage() {
StringBuffer b = new StringBuffer();
HttpConnection c = null;
TextBox t = null;
try {
long len = 0;
int ch = 0;
System.out.println("Read Page: " + getUrl);
c = (HttpConnection) Connector.open(getUrl);
InputStream is = c.openInputStream();
len = c.getLength();
if (len != -1) {
// Read exactly Content-Length bytes
// DEBUG: System.out.println("Content-Length: " + len);
for (int i = 0; i < len; i++)
if ((ch = is.read()) != -1)
b.append((char) ch);
} else {
// Read til the connection is closed.
// (Typical HTTP/1.0 script generated output)
while ((ch = is.read()) != -1) {
// DEBUG: System.out.println(""" + (char)ch + "" " +
// is.available() );
len = is.available(); // For HTTP 1.1 servers, chunked
// reads.
b.append((char) ch);
}
}
try {
is.close();
c.close();
} catch (Exception ce) {
System.out.println("Error closing connection");
}
try {
len = is.available();
System.out
.println("Inputstream failed to throw IOException after close");
} catch (IOException io) {
// Test to make sure available() is only valid while
// the connection is still open.,
}
t = new TextBox("Http Test", b.toString(), 1024, 0);
} catch (IOException ex) {
System.out.println("Exception reading from http");
if (c != null) {
try {
String s = c.getResponseMessage();
System.out.println(s);
if (s == null)
s = "No Response message";
t = new TextBox("Http Error", s, 1024, 0);
} catch (IOException e) {
ex.printStackTrace();
String s = ex.toString();
System.out.println(s);
if (s == null)
s = ex.getClass().getName();
t = new TextBox("Http Error", s, 1024, 0);
}
} else {
t = new TextBox("Http Error", "Could not open URL", 1024, 0);
}
}
t.addCommand(reloadCommand);
t.addCommand(exitCommand);
t.addCommand(headCommand);
t.setCommandListener(this);
display.setCurrent(t);
}
/*
* private void readPage() {
*
* StringBuffer b = new StringBuffer();
*
* HttpConnection c = null; TextBox t = null; try { c = ( HttpConnection
* )Connector.open( getUrl ); InputStream is = c.openInputStream(); int ch =
* 0; while ( (ch = is.read() ) != -1 ) { b.append( ( char )ch ); }
* is.close(); c.close();
*
* t = new TextBox( "Http Test", b.toString(), 1024, 0 );
* System.out.println( "String read from URL: " + getUrl + " - is: " +
* b.toString() ); } catch ( IOException ex ) { System.out.println(
* "Exception reading from http" ); if (c != null) { try { String s =
* c.getResponseMessage(); System.out.println( s ); if ( s == null ) s = "No
* Response message"; t = new TextBox( "Http Error", s, 1024, 0 ); } catch (
* IOException e ) { String s = ex.toString(); System.out.println( s ); if (
* s == null ) s = ex.getClass().getName(); t = new TextBox( "Http Error",
* s, 1024, 0 ); } } else { t = new TextBox( "Http Error", "Could not open
* URL", 1024, 0 ); } } t.addCommand( reloadCommand ); t.addCommand(
* exitCommand ); t.addCommand( headCommand ); t.setCommandListener( this );
* display.setCurrent( t ); }
*/
/*
* private void headPage() {
*
* StringBuffer b = new StringBuffer(); HttpConnection c = null; InputStream
* is = null;
*
* try { c = ( HttpConnection )Connector.open( headUrl );
* System.out.println( "Going to setRequestMethod()... " );
* c.setRequestMethod( HttpConnection.HEAD ); System.out.println( "Going to
* get Properties " ); b.append ( "URL: " + c.getURL( ) + "\nProtocol: " +
* c.getProtocol() + "\nHost: " + c.getHost() + "\nFile: " + c.getFile() +
* "\nRef: " + c.getRef() + "\nQuery: " + c.getQuery() + "\nPort: " +
* c.getPort() + "\nMethod: " + c.getRequestMethod()) ;
*
* System.out.println( "Gonna openInputStream... " ); is =
* c.openInputStream();
*
* System.out.println( "Going to get Properties after OpeninputStream" );
* b.append( "\nResponseCode: " + c.getResponseCode() + "\nResponseMessage:" +
* c.getResponseMessage() + "\nContentLength: " + c.getLength() +
* "\nContentType: " + c.getType() + "\nContentEncoding: " + c.getEncoding() +
* "\nContentExpiration: " + c.getExpiration() + "\nDate: " + c.getDate() +
* "\nLast-Modified: " + c.getLastModified() + "\n\n" );
*
* System.out.println( "Done getting properties after OpenInputStream " );
* int h = 0 ; while ( true ) { try {
*
* System.out.println( "Gonna get HeaderFieldKey... " ); String key =
* c.getHeaderFieldKey( h ); System.out.println( "Gonna get HeaderField... " );
* System.out.println( h + ", HeaderFieldKey is: " + key ); String value =
* c.getHeaderField( h ); System.out.println( h + ", HeaderField is: " +
* value ); b.append ( key + ": " + value + "\n" ); h++ ; } catch (
* Exception e ) { e.printStackTrace(); break; } }
*
* TextBox t = new TextBox( "Http Test", b.toString(), 1024, 0 );
* System.out.println ( b.toString() );
*
* t.addCommand( reloadCommand ); t.addCommand( exitCommand );
* t.setCommandListener( this ); display.setCurrent( t );
* } catch ( IOException ex ) { System.out.println( "Exception reading from
* http" ); ex.printStackTrace(); } finally { try { if ( is != null ) {
* is.close(); } if ( c != null ) { c.close(); } } catch( Exception e ) {
* e.printStackTrace(); }
* } }
*/
/**
* Pause signals the thread to stop by clearing the thread field. If stopped
* before done with the iterations it will be restarted from scratch later.
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything. The thread is signaled to stop and no
* result is produced.
*/
public void destroyApp(boolean unconditional) {
}
/*
* Respond to commands, including exit
*/
public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
} else if (c == reloadCommand)
readPage();
else if (c == headCommand)
headPage();
}
}
Invoke Servlet Midlet 1
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a servlet.
*/
public class InvokeServletMidlet1 extends MIDlet {
private Display display;
String url = "http://127.0.0.1:8080/examples/servlet/HelloServlet";
public InvokeServletMidlet1() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
invokeServlet(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Retrieve a grade....
*/
void invokeServlet(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
t = new TextBox("First Servlet", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
Invoke Servlet Midlet 2
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class InvokeServletMidlet2 extends MIDlet implements CommandListener {
Display display = null;
List menu = null;
TextBox input = null;
String user = null;
String url = "http://127.0.0.1:8080/examples/servlet/RequestServlet2";
static final Command backCommand = new Command("Back", Command.BACK, 0);
static final Command submitCommand = new Command("Submit", Command.OK, 2);
static final Command exitCommand = new Command("Exit", Command.STOP, 3);
String currentMenu = null;
public InvokeServletMidlet2() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
menu = new List("Invoke Servlet", Choice.IMPLICIT);
menu.append("Add a user", null);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
mainMenu();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
void mainMenu() {
display.setCurrent(menu);
}
public void addName() {
input = new TextBox("Enter first name:", "", 5, TextField.ANY);
input.addCommand(submitCommand);
input.addCommand(backCommand);
input.setCommandListener(this);
input.setString("");
display.setCurrent(input);
}
void invokeServlet(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("CONTENT-TYPE","application/x-www-form-urlencoded");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
String str = "name="+user;
byte postmsg[] = str.getBytes();
System.out.println("Length: "+str.getBytes());
for(int i=0;i<postmsg.length;i++) {
os.write(postmsg[i]);
}
// or you can easily do:
//os.write(("name="+user).getBytes());
os.flush();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.print((char)ch);
}
t = new TextBox("Second Servlet", b.toString(), 1024, 0);
t.addCommand(backCommand);
t.setCommandListener(this);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if (label.equals("Exit")) {
destroyApp(true);
} else if (label.equals("Back")) {
mainMenu();
} else if (label.equals("Submit")) {
user = input.getString();
try {
invokeServlet(url);
}catch(IOException e) {}
} else {
addName();
}
}
}
Jargoneer
/*
Wireless Java 2nd edition
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Jargoneer extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Command mExitCommand, mFindCommand, mCancelCommand;
private TextBox mSubmitBox;
private Form mProgressForm;
private StringItem mProgressString;
public Jargoneer() {
mExitCommand = new Command("Exit", Command.EXIT, 0);
mFindCommand = new Command("Find", Command.SCREEN, 0);
mCancelCommand = new Command("Cancel", Command.CANCEL, 0);
mSubmitBox = new TextBox("Jargoneer", "", 32, 0);
mSubmitBox.addCommand(mExitCommand);
mSubmitBox.addCommand(mFindCommand);
mSubmitBox.setCommandListener(this);
mProgressForm = new Form("Lookup progress");
mProgressString = new StringItem(null, null);
mProgressForm.append(mProgressString);
}
public void startApp() {
mDisplay = Display.getDisplay(this);
mDisplay.setCurrent(mSubmitBox);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c == mExitCommand) {
destroyApp(false);
notifyDestroyed();
}
else if (c == mFindCommand) {
// Show the progress form.
mDisplay.setCurrent(mProgressForm);
// Kick off the thread to do the query.
Thread t = new Thread(this);
t.start();
}
}
public void run() {
String word = mSubmitBox.getString();
String definition;
try { definition = lookUp(word); }
catch (IOException ioe) {
Alert report = new Alert(
"Sorry",
"Something went wrong and that " +
"definition could not be retrieved.",
null, null);
report.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(report, mSubmitBox);
return;
}
Alert results = new Alert("Definition", definition,
null, null);
results.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(results, mSubmitBox);
}
private String lookUp(String word) throws IOException {
HttpConnection hc = null;
InputStream in = null;
String definition = null;
try {
String baseURL = "http://65.215.221.148:8080/wj2/jargoneer?word=";
// Take a stab at parameter encoding, " " -> "+".
String url = baseURL + word.replace(" ", "+");
mProgressString.setText("Connecting...");
hc = (HttpConnection)Connector.open(url);
hc.setRequestProperty("Connection", "close");
in = hc.openInputStream();
mProgressString.setText("Reading...");
int contentLength = (int)hc.getLength();
if (contentLength == -1) contentLength = 255;
byte[] raw = new byte[contentLength];
int length = in.read(raw);
// Clean up.
in.close();
hc.close();
definition = new String(raw, 0, length);
}
finally {
try {
if (in != null) in.close();
if (hc != null) hc.close();
}
catch (IOException ignored) {}
}
return definition;
}
}
Midlet Servlet 2
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;
public class SecondMidletServlet extends MIDlet implements CommandListener {
Display display = null;
List menu = null;
TextBox input = null;
String user = null;
String url = "http://developer.java.sun.ru/servlet/RequestServlet";
static final Command backCommand = new Command("Back", Command.BACK, 0);
static final Command submitCommand = new Command("Submit", Command.OK, 2);
static final Command exitCommand = new Command("Exit", Command.STOP, 3);
String currentMenu = null;
public SecondMidletServlet() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
menu = new List("Invoke Servlet", Choice.IMPLICIT);
menu.append("Add a user", null);
menu.addCommand(exitCommand);
menu.setCommandListener(this);
mainMenu();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
void mainMenu() {
display.setCurrent(menu);
}
public void addName() {
input = new TextBox("Enter first name:", "", 5, TextField.ANY);
input.addCommand(submitCommand);
input.addCommand(backCommand);
input.setCommandListener(this);
input.setString("");
display.setCurrent(input);
}
void invokeServlet(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
String str = "name="+user;
byte postmsg[] = str.getBytes();
System.out.println("Length: "+str.getBytes());
for(int i=0;i<postmsg.length;i++) {
os.write(postmsg[i]);
}
// or you can easily do:
// os.write(("name="+user).getBytes());
os.flush();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.print((char)ch);
}
t = new TextBox("Second Servlet", b.toString(), 1024, 0);
t.addCommand(backCommand);
t.setCommandListener(this);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if (label.equals("Exit")) {
destroyApp(true);
} else if (label.equals("Back")) {
mainMenu();
} else if (label.equals("Submit")) {
user = input.getString();
try {
invokeServlet(url);
}catch(IOException e) {}
} else {
addName();
}
}
}
MIDlet to fetch a page using an HttpConnection
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
/**
* An example MIDlet to fetch a page using an HttpConnection.
*/
public class SecondExample extends MIDlet {
private Display display;
private String url = "http://www.javacourses.ru/hello.txt";
public SecondExample() {
display = Display.getDisplay(this);
}
/**
* This will be invoked when we activate the MIDlet.
*/
public void startApp() {
// Use the specified URL is overriden in the descriptor
try {
downloadPage(url);
} catch(IOException e) {
// handle the exception
}
}
private void downloadPage(String url) throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
TextBox t = null;
try {
long len = 0 ;
int ch = 0;
c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len =c.getLength() ;
if ( len != -1) {
// Read exactly Content-Length bytes
for (int i =0 ; i < len ; i++ )
if ((ch = is.read()) != -1)
b.append((char) ch);
} else {
// Read till the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available() ;
b.append((char)ch);
}
}
t = new TextBox("hello again....", b.toString(), 1024, 0);
} finally {
is.close();
c.close();
}
display.setCurrent(t);
}
/**
* Pause, discontinue....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
}
MIDlet to invoke a CGI script.
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a CGI script.
*/
public class FirstMidletServlet extends MIDlet {
private Display display;
String url = "http://developer.java.sun.ru/servlet/HelloServlet";
public FirstMidletServlet() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
invokeServlet(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Prepare connection and streams then invoke servlet.
*/
void invokeServlet(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
t = new TextBox("First Servlet", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
MIDlet to invoke a CGI script (GET method).
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a CGI script (GET method).
*/
public class InvokeCgiMidlet1 extends MIDlet {
private Display display;
String url = "http://www.javacourses.ru/cgi-bin/getgrade.cgi?idnum=182016";
public InvokeCgiMidlet1() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
getGrade(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Retrieve a grade....
*/
void getGrade(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
/*
String str = "?idnum=182016";
byte postmsg[] = str.getBytes();
for(int i=0;i<postmsg.length;i++) {
os.writeByte(postmsg[i]);
}
os.flush();
*/
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.println((char)ch);
}
t = new TextBox("Final Grades", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
MIDlet to invoke a CGI script (POST method is used)
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a CGI script (POST method is used).
*/
public class PostMidlet extends MIDlet {
private Display display;
String url = "http://developer.java.sun.ru/cgi-bin/pgrade.cgi";
public PostMidlet() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
getGrade(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Retrieve a grade....
*/
void getGrade(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
//start
String str = "name=163748";
byte postmsg[] = str.getBytes();
for(int i=0;i<postmsg.length;i++) {
os.write(postmsg[i]);
}
os.flush();
//end
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.println((char)ch);
}
t = new TextBox("Final Grades", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
MIDlet to invoke a CGI script (POST method is used) (2)
/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* An example MIDlet to invoke a CGI script (POST method is used).
*/
public class InvokeCgiMidlet2 extends MIDlet {
private Display display;
String url = "http://www.javacourses.ru/cgi-bin/pgrade.cgi";
public InvokeCgiMidlet2() {
display = Display.getDisplay(this);
}
/**
* Initialization. Invoked when we activate the MIDlet.
*/
public void startApp() {
try {
getGrade(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}
/**
* Pause, discontinue ....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
/**
* Retrieve a grade....
*/
void getGrade(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("CONTENT-TYPE","application/x-www-form-urlencoded");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
// send input
String str = "name=182016";
byte postmsg[] = str.getBytes();
for(int i=0;i<postmsg.length;i++) {
os.write(postmsg[i]);
}
os.flush();
is = c.openDataInputStream();
int ch;
// receive output
while ((ch = is.read()) != -1) {
b.append((char) ch);
System.out.println((char)ch);
}
t = new TextBox("Final Grades", b.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(c != null) {
c.close();
}
}
display.setCurrent(t);
}
}
Pass a cookie (stored in rms) between the MIDlet and a Java servlet.
/*--------------------------------------------------
* Cookie.java
*
* Pass a cookie (stored in rms) between the MIDlet
* and a Java servlet. The cookie is generated
* by the servlet on the first visit.
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;
public class Cookie extends MIDlet implements CommandListener
{
private Display display;
private TextBox tbMain;
private Form fmMain;
private Command cmExit;
private Command cmLogon;
private String cookie = null;
private RecordStore rs = null;
static final String REC_STORE = "rms_cookie";
private String url = "http://www.mycgiserver.ru/servlet/corej2me.CookieServlet";
public Cookie()
{
display = Display.getDisplay(this);
// Create commands
cmExit = new Command("Exit", Command.EXIT, 1);
cmLogon = new Command("Logon", Command.SCREEN, 2);
// Create the form, add commands, listen for events
fmMain = new Form("");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmLogon);
fmMain.setCommandListener(this);
// Read cookie if available
openRecStore();
readCookie();
// System.out.println("Client cookie: " + cookie);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{
closeRecStore(); // Close record store
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true);
}
catch (Exception e)
{
db("open " + e.toString());
}
}
public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db("close " + e.toString());
}
}
/*--------------------------------------------------
* Write cookie to rms
*-------------------------------------------------*/
public void writeRecord(String str)
{
byte[] rec = str.getBytes();
try
{
rs.addRecord(rec, 0, rec.length);
}
catch (Exception e)
{
db("write " + e.toString());
}
}
/*--------------------------------------------------
* Read cookie from rms
*-------------------------------------------------*/
public void readCookie()
{
try
{
byte[] recData = new byte[25];
int len;
if (rs.getNumRecords() > 0)
{
// Only one record will ever be written, safe to use "1"
if (rs.getRecordSize(1) > recData.length)
recData = new byte[rs.getRecordSize(1)];
len = rs.getRecord(1, recData, 0);
cookie = new String(recData);
}
}
catch (Exception e)
{
db("read " + e.toString());
}
}
/*--------------------------------------------------
* Send client request and recieve server response
*
* Client: If cookie exists, send it to the server
*
* Server: If cookie is sent back, this is the
* clients first request to the server. In
* that case, save the cookie. If no cookie
* sent, display server body (which indicates
* the last time the MIDlet contacted server).
*-------------------------------------------------*/
private void connect() throws IOException
{
InputStream iStrm = null;
ByteArrayOutputStream bStrm = null;
HttpConnection http = null;
try
{
// Create the connection
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// If you experience connection/IO problems, try
// removing the comment from the following line
//http.setRequestProperty("Connection", "close");
// 2) Send header information
if (cookie != null)
http.setRequestProperty("cookie", cookie);
System.out.println("Client cookie: " + cookie);
// 3) Send body/data - No data for this request
//----------------
// Server Response
//----------------
// 1) Get status Line
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
// 2) Get header information
String tmpCookie = http.getHeaderField("set-cookie");
System.out.println("server cookie: " + tmpCookie);
// Cookie will only be sent back from server only if
// client (us) did not send a cookie in the first place.
// If a cookie is returned, we need to save it to rms
if (tmpCookie != null)
{
writeRecord(tmpCookie);
// Update the MIDlet cookie variable
cookie = tmpCookie;
fmMain.append("First visit\n");
fmMain.append("Client : " + cookie + "\n");
}
else // No cookie sent from server
{
// 3) Get data, which is the last time of access
iStrm = http.openInputStream();
int length = (int) http.getLength();
String str;
if (length != -1)
{
byte serverData[] = new byte[length];
iStrm.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
}
// Append data to the form
fmMain.append("Last access:\n" + str + "\n");
}
}
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (bStrm != null)
bStrm.close();
if (http != null)
http.close();
}
}
/*--------------------------------------------------
* Process events
*-------------------------------------------------*/
public void commandAction(Command c, Displayable s)
{
// If the Command button pressed was "Exit"
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
else if (c == cmLogon)
{
try
{
// Logon to the servlet
connect();
}
catch (Exception e)
{
db("connect " + e.toString());
}
}
}
/*--------------------------------------------------
* Simple message to console for debug/errors
* When used with Exceptions we should handle the
* error in a more appropriate manner.
*-------------------------------------------------*/
private void db(String str)
{
System.err.println("Msg: " + str);
}
}
/*--------------------------------------------------
* CookieServlet.java
*
* Use a cookie to identify clients
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
//package corej2me; // Required for mycgiserver.ru
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.text.*;
public class CookieServlet extends HttpServlet
{
// Pool of client ID"s
private static int[] clientIDs = {123, 456, 789, 901, 225, 701};
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Get cookie from the header
Cookie[] cookies = req.getCookies();
//-------------------------------------------
// If cookie passed in...
// 1) Lookup the client ID in the database
// and save the last access date
// 2) Update the last access date in database
// 3) Return to the client date from step 1
//-------------------------------------------
if (cookies != null)
{
// There will be only one cookie
Cookie theCookie = cookies[0];
String id = theCookie.getValue();
// Lookup client ID and get last access date
String strLastAccess = lookupLastAccessDate(Integer.parseInt(id));
// Update database with current date
updateLastAccessDate(Integer.parseInt(id));
// Send back the last access date to the client
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.print(strLastAccess);
out.close();
}
else // No Cookie
{
//-------------------------------------------
// Generate a client ID. To keep the database
// from growing out of control, this will not
// generate a new ID for each client.
// Instead, grab a random ID from the array
// clientID"s[]. The end result is the same
// as far as the client is concerned.
//-------------------------------------------
// Random value between 0 and the number of
// entries in the client list array
int random = (int) Math.round(clientIDs.length * Math.random());
// Get the client ID to send in the cookie
int ID = clientIDs[random];
// Update database with current date
updateLastAccessDate(ID);
// Create new cookie and send ID in the header
Cookie cookie = new Cookie("ID", Integer.toString(ID));
res.addCookie(cookie);
}
}
/*--------------------------------------------------
* Update database with last access date for client ID
*-------------------------------------------------*/
private void updateLastAccessDate(int ID)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:acctInfo");
Statement stmt = con.createStatement();
// Create a date format
SimpleDateFormat format =
new SimpleDateFormat ("MMM dd-hh:mm aa");
String strDate = format.format(new java.util.Date());
ResultSet rs = stmt.executeQuery("UPDATE clientInfo set lastAccess = "" +
strDate + "" where clientID = " + ID);
}
catch (Exception e)
{ }
}
/*--------------------------------------------------
* Lookup the client ID in database and get the
* last access date
*-------------------------------------------------*/
private String lookupLastAccessDate(int id)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:acctInfo");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select lastAccess from clientInfo where clientID = " + id);
if (rs.next())
return rs.getString(1);
else
return null;
}
catch (Exception e)
{
return e.toString();
}
}
/*--------------------------------------------------
* Information about servlet
*-------------------------------------------------*/
public String getServletInfo()
{
return "CookieServlet 1.0 - John W. Muchow - www.corej2me.ru";
}
}
Patchy MIDlet
/*
Wireless Java 2nd edition
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.pki.*;
public class PatchyMIDlet extends MIDlet implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
private ServerSocketConnection mServerSocketConnection;
private boolean mTrucking = true;
public void startApp() {
mDisplay = Display.getDisplay(this);
if (mForm == null) {
mForm = new Form("PatchyMIDlet");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
}
Thread t = new Thread(this);
t.start();
mDisplay.setCurrent(mForm);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) { shutdown(); }
private void log(String text) { log(null, text); }
private void log(String label, String text) {
StringItem si = new StringItem(label, text);
//si.setLayout(Item.LAYOUT_NEWLINE_AFTER);
mForm.append(si);
}
private void shutdown() {
mTrucking = false;
try { mServerSocketConnection.close(); }
catch (IOException ioe) {}
}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
shutdown();
notifyDestroyed();
}
}
public void run() {
try {
mServerSocketConnection = (ServerSocketConnection)
Connector.open("socket://:80");
log("Startup complete.");
SocketConnection sc = null;
while (mTrucking) {
sc = (SocketConnection)
mServerSocketConnection.acceptAndOpen();
log("client: ", sc.getAddress());
// Strictly speaking, each client connection
// should be handled in its own thread. For
// simplicity, this implementation handles
// client connections inline.
Reader in = new InputStreamReader(
sc.openInputStream());
String line;
while ((line = readLine(in)) != null) ;
// Ignoring the request, send a response.
PrintStream out = new PrintStream(sc.openOutputStream());
out.print("HTTP/1.1 200 OK\r\n\r\n");
out.print(getMessage());
out.close();
in.close();
sc.close();
}
}
catch (Exception e) {
log("exception: ", e.toString());
}
}
private String readLine(Reader in) throws IOException {
// This is not efficient.
StringBuffer line = new StringBuffer();
int i;
while ((i = in.read()) != -1) {
char c = (char)i;
if (c == "\n") break;
if (c == "\r") ;
else line.append(c);
}
if (line.length() == 0) return null;
return line.toString();
}
private java.util.Random mRandom = new java.util.Random();
private String getMessage() {
int i = Math.abs(mRandom.nextInt()) % 5;
String s = null;
switch (i) {
case 0: s = "Above all the others we"ll fly"; break;
case 1: s = "There is no reason to hide"; break;
case 2: s = "I dreamed about Ray Charles last night"; break;
case 3: s = "Someone keeps moving my chair"; break;
case 4: s = "Joseph"s face was black as night"; break;
default: break;
}
return s;
}
}
Post MIDlet
/*
Wireless Java 2nd edition
Jonathan Knudsen
Publisher: Apress
ISBN: 1590590775
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class PostMIDlet extends MIDlet implements CommandListener, Runnable {
private Display mDisplay;
private Form mForm;
public PostMIDlet() {
mForm = new Form("Connecting...");
mForm.addCommand(new Command("Exit", Command.EXIT, 0));
mForm.setCommandListener(this);
}
public void startApp() {
if (mDisplay == null) mDisplay = Display.getDisplay(this);
mDisplay.setCurrent(mForm);
// Do network loading in a separate thread.
Thread t = new Thread(this);
t.start();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT)
notifyDestroyed();
}
public void run() {
HttpConnection hc = null;
InputStream in = null;
OutputStream out = null;
try {
String message = "name=Jonathan+Knudsen%21";
String url = getAppProperty("PostMIDlet-URL");
hc = (HttpConnection)Connector.open(url);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
hc.setRequestProperty("Content-Length",
Integer.toString(message.length()));
out = hc.openOutputStream();
out.write(message.getBytes());
in = hc.openInputStream();
int length = (int)hc.getLength();
byte[] data = new byte[length];
in.read(data);
String response = new String(data);
StringItem stringItem = new StringItem(null, response);
mForm.append(stringItem);
mForm.setTitle("Done.");
}
catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
mForm.append(stringItem);
mForm.setTitle("Done.");
}
finally {
try {
if (out != null) out.close();
if (in != null) in.close();
if (hc != null) hc.close();
}
catch (IOException ioe) {}
}
}
}
Sample to demonstrate Http GET and POST from MIDlet
/*** Chapter 5 Sample to demonstrate Http GET and POST from MIDlet ***/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class HttpTest1 extends MIDlet {
private Display display;
public HttpTest1() {
try {
//NOTE:Comment out the functionality which you don"t want to test
getBirthdayFromNameUsingGet("John");
getBirthdayFromNameUsingPost("John");
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}
/**
* MIDlet lifecycle functions
*/
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
/**
This function connects to web server and passes the parameter name to the
target in HTTP Get request. Upon successful connection, web server returns
birthday for "name".
This function also calls getConnectionInformation to retrieve properties of
HTTPConnection
**/
public void getBirthdayFromNameUsingGet(String name) throws IOException {
HttpConnection httpConn = null;
String url = "http://localhost:8080/examples/servlet/GetBirthday?name=" + name;
InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
// This function retrieves the information of this connection
getConnectionInformation(httpConn);
/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println(name+""s Birthday is " + sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}
} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
/**
This function connects to web server and passes the parameter name to the
target in HTTP POST request. Upon successful connection, web server returns
birthday for "name".
This function also calls getConnectionInformation to retrieve properties of
HTTPConnection
**/
public void getBirthdayFromNameUsingPost(String name) throws IOException {
HttpConnection httpConn = null;
String url = "http://localhost:8080/examples/servlet/GetBirthday";
InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language","en-US");
//Content-Type is must to pass parameters in POST Request
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// This function retrieves the information of this connection
getConnectionInformation(httpConn);
os = httpConn.openOutputStream();
String params;
params = "name=" + name;
os.write(params.getBytes());
/**Caution: os.flush() is controversial. It may create unexpected behavior
on certain mobile devices. Try it out for your mobile device **/
//os.flush();
// Read Response from the Server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println(name+""s Birthday is " + sb.toString());
} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
/*** After setup, attributes of the HttpConnection object can be retrived using
various get methods.
***/
void getConnectionInformation(HttpConnection hc) {
System.out.println("Request Method for this connection is " + hc.getRequestMethod());
System.out.println("URL in this connection is " + hc.getURL());
System.out.println("Protocol for this connection is " + hc.getProtocol()); // It better be HTTP:)
System.out.println("This object is connected to " + hc.getHost() + " host");
System.out.println("HTTP Port in use is " + hc.getPort());
System.out.println("Query parameter in this request are " + hc.getQuery());
}
}
Send client request and Get server response
/*--------------------------------------------------
* ViewFile.java
*
* Send client request (method, header, body)
* Get server response (status, header, body)
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class ViewFile extends MIDlet
{
private String url = "http://www.corej2me.ru/midpbook_v1e1/ch14/getHeaderInfo.txt";
public void startApp()
{
try
{
processRequest();
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
private void processRequest() throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
try
{
// Create the connection
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information (this header is optional)
http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
// http.setRequestProperty("If-Modified-Since", "Mon, 16 Jul 2001 22:54:26 GMT");
// If you experience IO problems, try
// removing the comment from the following line
//http.setRequestProperty("Connection", "close");
// 3) Send body/data - No data for this request
//----------------
// Server Response
//----------------
System.out.println("url: " + url);
System.out.println("-------------------------");
// 1) Get status Line
System.out.println("Msg: " + http.getResponseMessage());
System.out.println("Code: " + http.getResponseCode());
// 2) Get header information
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
System.out.println("field 0: " + http.getHeaderField(0));
System.out.println("field 1: " + http.getHeaderField(1));
System.out.println("field 2: " + http.getHeaderField(2));
System.out.println("-------------------------");
System.out.println("key 0: " + http.getHeaderFieldKey(0));
System.out.println("key 1 : " + http.getHeaderFieldKey(1));
System.out.println("key 2: " + http.getHeaderFieldKey(2));
System.out.println("-------------------------");
System.out.println("content: " + http.getHeaderField("content-type"));
System.out.println("date: " + http.getHeaderField("date"));
System.out.println("last-modified: " + http.getHeaderField("last-modified"));
System.out.println("-------------------------");
// 3) Get data (show the file contents)
String str;
iStrm = http.openInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
iStrm.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// Read data one character at a time
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("File Contents: " + str);
//-----------------------------
// Show connection information
//-----------------------------
System.out.println("Host: " + http.getHost());
System.out.println("Port: " + http.getPort());
System.out.println("Type: " + http.getType());
// System.out.println("File: " + http.getFile());
// System.out.println("Protocol: " + http.getProtocol());
// System.out.println("URL: " + http.getURL());
// System.out.println("Query: " + http.getQuery());
}
}catch(Exception e){
e.printStackTrace();
}finally{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){ }
}
Socket connection
/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: socketconnection
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: socketconnection.jar
MIDlet-1: socketconnection, , socketconnection
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class socketconnection extends MIDlet implements CommandListener {
private Command exit, start;
private Display display;
private Form form;
public socketconnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Read Write Socket");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
try
{
StreamConnection connection = (StreamConnection) Connector.open("socket://www.myserver.ru:80");
PrintStream output =
new PrintStream(connection.openOutputStream() );
output.println( "GET /my.html HTTP/0.9\n\n" );
output.flush();
InputStream in = connection.openInputStream();
int ch;
while( ( ch = in.read() ) != -1 )
{
System.out.print( (char) ch );
}
in.close();
output.close();
connection.close();
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access socket.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
}
}
Socket MIDlet
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class SocketMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Form addressForm;
private Form connectForm;
private Form displayForm;
private TextField serverName;
private TextField serverPort;
private StringItem messageLabel;
private StringItem errorLabel;
private Command okCommand;
private Command exitCommand;
private Command backCommand;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(addressForm);
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
}
}
public void run() {
InputStream is = null;
OutputStream os = null;
StreamConnection socket = null;
try {
String server = serverName.getString();
String port = serverPort.getString();
String name = "socket://" + server + ":" + port;
socket = (StreamConnection)Connector.open(name, Connector.READ_WRITE);
} catch (Exception ex) {
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
}
try {
// Send a message to the server
String request = "GET / HTTP/1.0\n\n";
os = socket.openOutputStream();
os.write(request.getBytes());
os.close();
// Read the server"s reply, up to a maximum
// of 128 bytes.
is = socket.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
socket.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
Alert alert = new Alert("I/O Error",
"An error occurred while communicating with the server.",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
} finally {
// Close open streams and the socket
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException ex1) {
}
try {
if (os != null) {
os.close();
os = null;
}
} catch (IOException ex1) {
}
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (IOException ex1) {
}
}
}
private void initialize() {
display = Display.getDisplay(this);
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
// The address form
addressForm = new Form("Socket Client");
serverName = new TextField("Server name:", "", 256, TextField.ANY);
serverPort = new TextField("Server port:", "", 8, TextField.NUMERIC);
addressForm.append(serverName);
addressForm.append(serverPort);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
// The connect form
connectForm = new Form("Connecting");
messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
// The display form
displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);
}
}
Timer Server
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.InterruptedIOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TimeMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Form addressForm;
private Form connectForm;
private Form displayForm;
private Command backCommand;
private Command exitCommand;
private Command okCommand;
private StringItem messageLabel;
private TextField serverName;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(addressForm);
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
}
}
public void run() {
DatagramConnection conn = null;
display.setCurrent(connectForm);
try {
// Build the name string for the Connector open method
String server = serverName.getString();
String name = "datagram://" + server + ":" + 13;
conn = (DatagramConnection)Connector.open(name,
Connector.READ_WRITE, false);
// Build and send an empty datagram
Datagram dg = conn.newDatagram(10);
dg.setData("Hello".getBytes(), 0, 5);
conn.send(dg);
// Receive the reply
Datagram rdg = conn.newDatagram(512);
conn.receive(rdg);
messageLabel.setText(new String(rdg.getData(), 0, rdg.getLength()));
display.setCurrent(displayForm);
} catch (InterruptedIOException iex) {
display.callSerially(new Runnable() {
public void run() {
Alert alert = new Alert("No Reply",
"No reply was received.\n" +
"Please check the server address and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
}
});
return;
} catch (Exception ex) {
display.callSerially(new Runnable() {
public void run() {
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
}
});
return;
} catch (Error err) {
System.out.println(err);
err.printStackTrace();
}
}
private void initialize() {
display = Display.getDisplay(this);
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
// The address form
addressForm = new Form("Network Time");
serverName = new TextField("Time Server name:", "tock.usno.navy.mil",
256, TextField.ANY);
addressForm.append(serverName);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
// The connect form
connectForm = new Form("Sending");
messageLabel = new StringItem(null,
"Sending the datagram...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
// The display form
displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);
}
}
Time Server
/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
public class TimeServer {
public static void main(String[] args) {
try {
Calendar cal = Calendar.getInstance();
DatagramConnection receiver =
(DatagramConnection)Connector.open("datagram://:13");
byte[] buffer = new byte[256];
Datagram dgram = receiver.newDatagram(buffer, buffer.length);
for (;;) {
dgram.setLength(buffer.length);
// Wait for somebody to call...
receiver.receive(dgram);
// Get the time and store it in the buffer
cal.setTime(new Date());
String time = cal.toString();
byte[] dataBytes = time.getBytes();
System.arraycopy(dataBytes, 0, buffer, 0, dataBytes.length);
// Send back the reply
dgram.setLength(dataBytes.length);
receiver.send(dgram);
}
} catch (IOException ex) {
System.out.println("IOException: " + ex);
}
}
}
Use GET or POST to communicate with a Java servlet.
/*--------------------------------------------------
* GetNpost.java
*
* Use GET or POST to communicate with a Java servlet.
* The servlet will search a database for the balance
* of an account.
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class GetNpost extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // The main form
private Alert alError; // Alert to error message
private Command cmGET; // Request method GET
private Command cmPOST; // Request method Post
private Command cmExit; // Command to exit the MIDlet
private TextField tfAcct; // Get account number
private TextField tfPwd; // Get password
private StringItem siBalance;// Show account balance
private String errorMsg = null;
public GetNpost()
{
display = Display.getDisplay(this);
// Create commands
cmGET = new Command("GET", Command.SCREEN, 2);
cmPOST = new Command("POST", Command.SCREEN, 3);
cmExit = new Command("Exit", Command.EXIT, 1);
// Textfields
tfAcct = new TextField("Account:", "", 5, TextField.NUMERIC);
tfPwd = new TextField("Password:", "", 10, TextField.ANY | TextField.PASSWORD);
// Balance string item
siBalance = new StringItem("Balance: $", "");
// Create Form, add commands & componenets, listen for events
fmMain = new Form("Account Information");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmGET);
fmMain.addCommand(cmPOST);
fmMain.append(tfAcct);
fmMain.append(tfPwd);
fmMain.append(siBalance);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmGET || c == cmPOST)
{
try
{
if (c == cmGET)
lookupBalance_withGET();
else
lookupBalance_withPOST();
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
/*--------------------------------------------------
* Access servlet using GET
*-------------------------------------------------*/
private void lookupBalance_withGET() throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed at the end of url for GET
String url = "http://www.mycgiserver.ru/servlet/corej2me.GetNpostServlet" + "?" +
"account=" + tfAcct.getString() + "&" +
"password=" + tfPwd.getString();
try
{
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information - none
// 3) Send body/data - data is at the end of URL
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Access servlet using POST
*-------------------------------------------------*/
private void lookupBalance_withPOST() throws IOException
{
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed as a separate stream for POST (below)
String url = "http://www.mycgiserver.ru/servlet/corej2me.GetNpostServlet";
try
{
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
//----------------
// Client Request
//----------------
// 1) Send request type
http.setRequestMethod(HttpConnection.POST);
// 2) Send header information. Required for POST to work!
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");
// 3) Send data/body
// Write account number
byte data[] = ("account=" + tfAcct.getString()).getBytes();
oStrm.write(data);
// Write password
data = ("&password=" + tfPwd.getString()).getBytes();
oStrm.write(data);
// For 1.0.3 remove flush command
// See the note at the bottom of this file
// oStrm.flush();
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Process a response from a server
*-------------------------------------------------*/
private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
{
//Reset error message
errorMsg = null;
// 1) Get status Line
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
// 2) Get header information - none
// 3) Get body (data)
int length = (int) http.getLength();
String str;
if (length != -1)
{
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
// Update the string item on the display
siBalance.setText(str);
return true;
}
else
// Use message from the servlet
errorMsg = new String( http.getResponseMessage());
return false;
}
/*--------------------------------------------------
* Show an Alert
*-------------------------------------------------*/
private void showAlert(String msg)
{
// Create Alert, use message returned from servlet
alError = new Alert("Error", msg, null, AlertType.ERROR);
// Set Alert to type Modal
alError.setTimeout(Alert.FOREVER);
// Display the Alert. Once dismissed, display the form
display.setCurrent(alError, fmMain);
}
}
/*
The call to flush() uses a feature of HTTP 1.1 that allows data to be
sent in smaller loads. When calling flush() or sending a large
amount of data (in version 1.0.3) chunked encoding is used.
If you are using an HTTP 1.0 server or proxy server the chunked
transfer may cause problems.
You can avoid the chunking behavior with small transactions by just
calling close() where you were using flush(). For larger transactions
you need to buffer your output so a single write() and close() are
issued to the output stream.
*/
/*--------------------------------------------------
* GetNpostServlet.java
*
* Show how GET and POST from client can access and
* process the same data.
* Account information is maintained in a database
* (connecting with jdbc)
*
* Table: acctInfo
* Columns:
* account - integer
* password - varchar
* balance - integer
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
//package corej2me; // Required for mycgiserver.ru
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class GetNpostServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Same code appears in doPost()
// Shown both places to emphasize that data is received thru
// different means (environment variable vs stream),
// yet processed the same inside the servlet
String acct = req.getParameter("account"),
pwd = req.getParameter("password");
String balance = accountLookup(acct, pwd);
if (balance == null)
{
res.sendError(res.SC_BAD_REQUEST, "Unable to locate account.");
return;
}
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Same code appears in doGet()
// Shown both places to emphasize that data is received thru
// different means (stream vs environment variable),
// yet processed the same inside the servlet
String acct = req.getParameter("account"),
pwd = req.getParameter("password");
String balance = accountLookup(acct, pwd);
if (balance == null)
{
res.sendError(res.SC_BAD_REQUEST, "Unable to locate account.");
return;
}
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}
/*--------------------------------------------------
* Lookup bank account balance in database
*-------------------------------------------------*/
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer("");
try
{
// These will vary depending on your server/database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:acctInfo");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select balance from acctInfo where account = " +
acct + "and password = "" + pwd + """);
if (rs.next())
return rs.getString(1);
else
return null;
}
catch (Exception e)
{
return e.toString();
}
}
/*--------------------------------------------------
* Information about servlet
*-------------------------------------------------*/
public String getServletInfo()
{
return "GetNpostServlet 1.0 - John W. Muchow - www.corej2me.ru";
}
}
Use Java servlets sessions to tally golf scores.
/*--------------------------------------------------
* Url_rewrite.java
*
* Use Java servlets sessions to tally golf scores.
* Session management is done using url-rewriting.
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class Url_rewrite extends MIDlet implements CommandListener
{
private Display display; // Reference to display object
private Form fmMain; // The main form
private TextField tfScore; // Enter new score
private int indxTextField; // Index on of the textfield
private StringItem siTotal; // Running total
private Command cmExit; // A Command to exit the MIDlet
private Command cmUpdate; // Update score on servlet
private int holeNumber = 1; // Current hole
private static final int MAX_HOLES = 18;
private String url = "http://www.mycgiserver.ru/servlet/corej2me.Url_rewriteServlet";
public Url_rewrite()
{
display = Display.getDisplay(this);
// Enter scores
tfScore = new TextField("Enter score for Hole #1", "", 2, TextField.NUMERIC);
// Current running total
siTotal = new StringItem("Total: ", "");
// Commands
cmExit = new Command("Exit", Command.EXIT, 1);
cmUpdate = new Command("Send", Command.SCREEN,2);
// Create Form, add components, listen for events
fmMain = new Form("");
// Save index of textfield, it is removed
// after entering 18 values
indxTextField = fmMain.append(tfScore);
fmMain.append(siTotal);
fmMain.addCommand(cmExit);
fmMain.addCommand(cmUpdate);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
/*--------------------------------------------------
* Process events
*-------------------------------------------------*/
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
else if (c == cmUpdate) // Send score for next hole
{
// If nothing in the text field or max scores entered
if (tfScore.getString().equals("") || holeNumber > MAX_HOLES)
return;
else
{
try
{
// Update the score on remote server
updateTotal(tfScore.getString());
// If entered the maximum, remove the
// textfield from the form
if (++holeNumber > MAX_HOLES)
{
fmMain.delete(indxTextField);
return;
}
// Change the label & reset contents
tfScore.setLabel("Enter score for Hole #" + holeNumber);
tfScore.setString("");
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
}
}
/*--------------------------------------------------
* Send client request. Receive server response
*
* Client: Send score for next hole.
*
* Server: Check for custom header "Custom-newURL"
* If found, update the MIDlet URL for all
* future requests. Any data returned is
* current total for all scores entered.
*-------------------------------------------------*/
private void updateTotal(String score) throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
boolean ret = false;
try
{
// When using GET, append data onto the url
String completeURL = url + "?" + "score=" + score;
http = (HttpConnection) Connector.open(completeURL);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information - none
// If you experience connection/IO problems, try
// removing the comment from the following line
//http.setRequestProperty("Connection", "close");
// 3) Send body/data - data is at the end of URL
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// 1) Get status Line - ignore for now
// System.out.println("Msg: " + http.getResponseMessage());
// System.out.println("Code: " + http.getResponseCode());
// 2) Get header information
// See if header includes a rewritten url
// if yes, update url for all future servlet requests
String URLwithID = http.getHeaderField("Custom-newURL");
if (URLwithID != null)
url = URLwithID;
// 3) Get body/data - the new running total is returned
String str;
int length = (int) http.getLength();
if (length != -1)
{
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
// Update the stringitem that shows total
siTotal.setText(str);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
}
}
/*--------------------------------------------------
* Url_rewriteServlet.java
*
* Use url-rewriting to manage sessions.
* Keeps a running total of golf scores for a
* round of 18 holes (client sends score for each
* hole, one at a time).
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
//package corej2me; // Required for mycgiserver.ru
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Url_rewriteServlet extends HttpServlet
{
/*--------------------------------------------------
* Initialize the servlet
*-------------------------------------------------*/
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
/*--------------------------------------------------
* Handle a GET request from client
*-------------------------------------------------*/
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
try
{
// Get session information
HttpSession session = req.getSession(true);
// If a new session, we need to rewrite the URL for client
if (session.isNew())
{
// Get the URL that got us here
String incomingURL = HttpUtils.getRequestURL(req).toString();
// Encode by adding session ID onto URL
String URLwithID = res.encodeURL(incomingURL);
// Send back a header to client with new re-written URL
res.setHeader("Custom-newURL", URLwithID);
}
// Get the next score (parameter) passed in
int nextScore = Integer.parseInt(req.getParameter("score"));
// Get the ongoing total saved as part of the session
// Convert to an integer "object"
Integer sessionTotal = (Integer) session.getValue("sessionTotal");
// Running total from session and score passed in
int runningTotal = nextScore;
if (sessionTotal != null)
runningTotal += sessionTotal.intValue();
// Update the session total, must save as an "object"
session.putValue("sessionTotal", new Integer(runningTotal));
// Send back to client the new running total
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.write(Integer.toString(runningTotal));
out.close();
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
/*--------------------------------------------------
* Information about servlet
*-------------------------------------------------*/
public String getServletInfo()
{
return "Url_rewriteServlet 1.0 - John W. Muchow - www.corej2me.ru";
}
}
www.amazon.com Book Ranking MIDlet
/*
* J2ME in a Nutshell By Kim Topley ISBN: 0-596-00253-X
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class RankingMIDlet extends MIDlet implements CommandListener, Runnable {
private Command exitCommand;
private Command okCommand;
private Command cancelCommand;
private Command newCommand;
private Display display;
private TextField isbnField;
private StringItem isbnDisplay;
private StringItem titleDisplay;
private StringItem rankingDisplay;
private StringItem reviewDisplay;
private Form isbnForm;
private Form searchForm;
private Form resultForm;
private BookInfo searchBookInfo;
private Thread searchThread;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(isbnForm);
}
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
} else if (cmd == okCommand) {
String isbn = isbnField.getString().trim();
if (!isbn.equals("")) {
searchForBook(new BookInfo(isbn));
}
} else if (cmd == cancelCommand) {
searchThread = null;
isbnField.setString(null);
display.setCurrent(isbnForm);
} else if (cmd == newCommand) {
isbnField.setString(null);
display.setCurrent(isbnForm);
}
}
public void searchForBook(BookInfo info) {
searchBookInfo = info;
isbnDisplay.setText(info.getIsbn().trim());
display.setCurrent(searchForm);
searchThread = new Thread(this);
searchThread.start();
}
public void run() {
try {
boolean found = Fetcher.fetch(searchBookInfo);
if (searchThread == Thread.currentThread()) {
if (found && searchBookInfo.getTitle() != null) {
titleDisplay.setText(searchBookInfo.getTitle());
rankingDisplay
.setText(searchBookInfo.getRanking() == 0 ? ""
: String.valueOf(searchBookInfo
.getRanking()));
reviewDisplay.setText(searchBookInfo.getReviews() == 0 ? ""
: String.valueOf(searchBookInfo.getReviews()));
display.setCurrent(resultForm);
} else {
Alert alert = new Alert("Book not found", null, null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
alert.setString("No book with ISBN "
+ searchBookInfo.getIsbn() + " was found.");
isbnField.setString(null);
display.setCurrent(alert, isbnForm);
}
}
} catch (Throwable ex) {
if (searchThread == Thread.currentThread()) {
Alert alert = new Alert("Search Failed", null, null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
alert.setString("Search failed:\n" + ex.getMessage());
isbnField.setString(null);
display.setCurrent(alert, isbnForm);
}
}
}
private void initialize() {
display = Display.getDisplay(this);
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
cancelCommand = new Command("Cancel", Command.CANCEL, 0);
newCommand = new Command("New", Command.SCREEN, 1);
isbnForm = new Form("Book Query");
isbnForm.append("Enter an ISBN and press OK:");
isbnField = new TextField("", null, 10, TextField.ANY);
isbnForm.append(isbnField);
isbnForm.addCommand(okCommand);
isbnForm.addCommand(exitCommand);
searchForm = new Form("Book Search");
searchForm.append("Searching for ISBN\n");
isbnDisplay = new StringItem(null, null);
searchForm.append(isbnDisplay);
searchForm.append("\nPlease wait....");
searchForm.addCommand(cancelCommand);
resultForm = new Form("Search Results");
titleDisplay = new StringItem("Book title: ", null);
rankingDisplay = new StringItem("Ranking: ", null);
reviewDisplay = new StringItem("Reviews: ", null);
resultForm.append(titleDisplay);
resultForm.append(rankingDisplay);
resultForm.append(reviewDisplay);
resultForm.addCommand(newCommand);
resultForm.addCommand(exitCommand);
// Register for events from all of the forms
isbnForm.setCommandListener(this);
searchForm.setCommandListener(this);
resultForm.setCommandListener(this);
}
}
class Fetcher {
private static final String BASE_URL = "http://www.amazon.ru";
private static final String QUERY_URL = BASE_URL
+ "/exec/obidos/search-handle-form/0";
private static final int MAX_REDIRECTS = 5;
// Fetches the title, ranking and review count
// for a book with a given ISBN.
public static boolean fetch(BookInfo info) throws IOException {
InputStream is = null;
OutputStream os = null;
HttpConnection conn = null;
int redirects = 0;
try {
String isbn = info.getIsbn();
String query = "index=books&field-keywords=" + isbn + "\r\n";
String requestMethod = HttpConnection.POST;
String name = QUERY_URL;
while (redirects < MAX_REDIRECTS) {
conn = (HttpConnection) Connector.open(name,
Connector.READ_WRITE);
// Send the ISBN number to perform the query
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("Connection", "Close");
if (requestMethod.equals(HttpConnection.POST)) {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
os = conn.openOutputStream();
os.write(query.getBytes());
os.close();
os = null;
}
// Read the response from the server
is = conn.openInputStream();
int code = conn.getResponseCode();
// If we get a redirect, try again at the new location
if ((code >= HttpConnection.HTTP_MOVED_PERM && code <= HttpConnection.HTTP_SEE_OTHER)
|| code == HttpConnection.HTTP_TEMP_REDIRECT) {
// Get the URL of the new location (always absolute)
name = conn.getHeaderField("Location");
is.close();
conn.close();
is = null;
conn = null;
if (++redirects > MAX_REDIRECTS) {
// Too many redirects - give up.
break;
}
// Choose the appropriate request method
requestMethod = HttpConnection.POST;
if (code == HttpConnection.HTTP_MOVED_TEMP
|| code == HttpConnection.HTTP_SEE_OTHER) {
requestMethod = HttpConnection.GET;
}
continue;
}
String type = conn.getType();
if (code == HttpConnection.HTTP_OK && type.equals("text/html")) {
info.setFromInputStream(is);
return true;
}
}
} catch (Throwable t) {
System.out.println(t);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException ex) {
}
}
}
return false;
}
}
/**
* A class that represents a book listing at an online book set, including the
* number of reviews for the book and its sales ranking.
*/
class BookInfo {
int id; // Used when persisting
String isbn; // The book ISBN
String title; // The book title
int reviews; // Number of reviews
int ranking; // Current ranking
int lastReviews; // Last review count
int lastRanking; // Last ranking
public BookInfo(String isbn) {
this.isbn = isbn;
}
public String getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public int getReviews() {
return reviews;
}
public int getRanking() {
return ranking;
}
public int getLastReviews() {
return lastReviews;
}
public int getLastRanking() {
return lastRanking;
}
// Installs details parsed from an input stream
public void setFromInputStream(InputStream is) {
// Use an InputHelper to search the input
InputHelper helper = new InputHelper(is);
try {
// Default new values to current values
int newRanking = this.ranking;
int newReviews = this.reviews;
boolean found = helper.moveAfterString("buying info: ");
if (!found) {
return;
}
// Gather the title from the rest of this line
StringBuffer titleBuffer = helper.getRestOfLine();
// Look for the number of reviews
found = helper.moveAfterString("Based on ");
if (!found) {
return;
}
// Gather the number of reviews from the current location
String reviewString = helper.gatherNumber();
// Look for the sales rank
found = helper.moveAfterString("Sales Rank: ");
if (!found) {
return;
}
// Gather the number from the current location
String rankingString = helper.gatherNumber();
// Having safely found everything, set the new title
title = titleBuffer.toString().trim();
// Now convert the reviews and ranking to integers.
// If they fail to convert, just leave the existing
// values.
try {
newRanking = Integer.parseInt(rankingString);
} catch (NumberFormatException ex) {
}
if (newRanking != ranking) {
lastRanking = ranking;
ranking = newRanking;
if (lastRanking == 0) {
// First time, set last and current
// to the same value
lastRanking = ranking;
}
}
try {
newReviews = Integer.parseInt(reviewString);
} catch (NumberFormatException ex){
}
if (newReviews != reviews) {
lastReviews = reviews;
reviews = newReviews;
if (lastReviews == 0) {
// First time, set last and current
// to the same value
lastReviews = reviews;
}
}
} catch (IOException ex) {
} finally {
// Allow garbage collection
helper.dispose();
helper = null;
}
}
}
//A class that scans through an input
//stream for strins without reading the
//entire stream into a large string.
class InputHelper {
// Size of the input buffer
private static final int BUFFER_SIZE = 1024;
// The input buffer
private final char[] buffer = new char[BUFFER_SIZE];
// Number of characters left in the buffer
private int charsLeft;
// Index of the next character in the buffer
private int nextChar;
// InputStreamReader used to map to Unicode
private InputStreamReader reader;
// Constructs a helper to read a given stream
public InputHelper(InputStream is) {
reader = new InputStreamReader(is);
}
// Cleans up when no longer needed
public void dispose() {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
}
reader = null;
}
}
// Looks for a given string in the input
// stream and positions the stream so that the
// next character read is one beyond the string.
// Returns true if the string was found, false if
// not (and the stream will have been completely read).
public boolean moveAfterString(String str) throws IOException {
char[] chars = str.toCharArray();
int count = chars.length;
char firstChar = chars[0];
char c = (char) 0;
for (;;) {
if (c != firstChar && !findNext(firstChar)) {
// Reached the end of the input stream
return false;
}
boolean mismatch = false;
for (int i = 1; i < count; i++) {
c = getNext();
if (c != chars[i]) {
mismatch = true;
break;
}
}
if (!mismatch) {
return true;
}
// Mismatch. "c" has the first mismatched
// character - start the loop again with
// that character. This is necessary because we
// could have found "wweb" while looking for "web"
}
}
// Gets the characters for a number, ignoring
// the grouping separator. The number starts at the
// current input position, but any leading non-numerics
// are skipped.
public String gatherNumber() throws IOException {
StringBuffer sb = new StringBuffer();
boolean gotNumeric = false;
for (;;) {
char c = getNext();
// Skip until we find a digit.
boolean isDigit = Character.isDigit(c);
if (!gotNumeric && !isDigit) {
continue;
}
gotNumeric = true;
if (!isDigit) {
if (c == "." || c == ",") {
continue;
}
break;
}
sb.append(c);
}
return sb.toString();
}
// Gets the balance of the current line
// and returns it as a StringBuffer
public StringBuffer getRestOfLine() throws IOException {
StringBuffer sb = new StringBuffer();
char c;
for (;;) {
c = getNext();
if (c == "\n" || c == (char) 0) {
break;
}
sb.append(c);
}
return sb;
}
// Gets the next character from the stream,
// returning (char)0 when all input has been read.
private char getNext() throws IOException {
if (charsLeft == 0) {
charsLeft = reader.read(buffer, 0, BUFFER_SIZE);
if (charsLeft < 0) {
return (char) 0;
}
nextChar = 0;
}
charsLeft--;
return buffer[nextChar++];
}
// Finds the next instance of a given character in the
// input stream. The input stream is positioned after
// the located character. If EOF is reached without
// finding the character, false is returned.
private boolean findNext(char c) throws IOException {
for (;;) {
if (charsLeft == 0) {
charsLeft = reader.read(buffer, 0, BUFFER_SIZE);
if (charsLeft < 0) {
return false;
}
nextChar = 0;
}
charsLeft--;
if (c == buffer[nextChar++]) {
return true;
}
}
}
}