Http Connecton in J2ME
There is 1 class (Connector) and 7 connection interfaces (Connection, ContentConnection, DatagramConnection, InputConnection, OutputConnection, StreamConnection, and StreamConnectionNotifier) defined in the Generic Connection framework. They can be found in the javax.microedition.io package that comes with J2ME CLDC. Please note that there is no implementation of the connection interfaces at the CLDC level. The actual implementation is left to MIDP.
The 7 connection interfaces define the abstractions of 6 basic types of communications: basic serial input, basic serial output, datagrams communications, sockets communications, notification mechanism in a client-server communication, and basic HTTP communication with a Web server.
The relationships between these interfaces are illustrated in the following diagram:
As shown in the figure, Connection is the base interface and the root of the connection interface hierarchy. All the other connection interfaces derive from Connection. StreamConnection derives from InputConnection and OutputConnection. It defines both the input and output capabilities for a stream connection. ContentConnection derives from StreamConnection. It adds three additional methods from MIME handling on top of the I/O methods in StreamConnection.
The Connector class is the core of Generic Connection framework. The reason we say that is because all connection objects we mentioned above are created by the static method open defined in Connector class. Different types of communication can be created by the same method with different parameters. The connection could be file I/O, serial port communication, datagram connection, or an http connection depending on the string parameter passed to the method. Such design makes J2ME implementation very extensible and flexible in supporting new devices and products.
Here is how the method is being used:
Connector.open(String connect);
The parameter connect_is a String variable. It has a URL-like format: {protocol}:[{target}][{params}] and it consists of three parts: protocol, target, and params.
protocol dictates what type of connection will be created by the method. There are several possible values for protocol: file, socket, comm, datagram and http. file indicates that the connection will be used for file I/O, comm indicates that the connection will be used for serial port communication, and http indicates that the connection is created for accessing web servers.
target can be a host name, a network port number, a file name, or a communication port number.
params is optional, it specifies the additional information needed to complete the connect string.
The following examples illustrate how to use the open method to create different types of communication based on different protocols:
HTTP communication:
Connection hc = Connector.open("http://www.wirelessdevnet.com");
Stream-based Socket communication:
Connection sc = Connector.open("socket://localhost:9000");
Datagram-based socket communication:
Connection dc = Connector.open("datagram://:9000");
Serial port communication:
Connection cc = Connector.open("comm:0;baudrate=9000");
File I/O
Connection fc = Connector.open("file://foo.dat");
The HttpConnection Class
The HttpConnection class is defined in J2ME MIDP to allow developer to handle http connections in their wireless applications. The HttpConnection class is guaranteed available on all MIDP devices.
Theoretically you may use either sockets, or datagrams for remote communication in your J2ME applications if your MIDP device manufacturer supports them. But this creates a portability issue for your applications, because you can’t always count on that other device manufacturers will support them as well. This means that your program may run on one MIDP device but fail on others. So you should consider using the HttpConnection class in your application first, because HTTPConnection is mandatory for all MIDP implementations.
In this section, a complete sample program using HttpConnection is shown in the next section.
The HttpConnection interface derives from the ContentConnection interface in CLDC. It inherits all I/O stream methods from StreamConnection, all the MIME handling methods from ContentConnection and adds several additional methods for handling http protocol specific needs.
Here is a laundry list of all the methods available in HttpConnection:
Input Stream and OutputStream
An input stream can be used to read contents from a Web server while output stream can be used to send request to a Web server. These streams can be obtained from the HttpConnection object after the connection has been established with the Web Server. In the following example, an http connection is established with Web server www.wirelessdevnet.com at port 80 (the default http port). Then an input stream is obtained for reading response from the Web:
HttpConnection hc = (HttpConnection);
Connector.open("http://www.wirelessdevnet.com");
InputStream is = new hc.openInputStream();
int ch; // Check the Content-Length first
long len = hc.getLength();
if(len!=-1)
{
for(int i = 0;i<len;i++)
if((ch = is.read())!= -1)
System.out.print((char) ch));
}
else
{
// if the content-length is not available
while ((ch = is.read()) != -1)
System.out.print((char) ch));
}
is.close();
hc.close();
The below sample code is for sending the bulky data over network by using StringBuffer
SAMPLE CODE
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class Sample1 extends MIDlet
implements CommandListener {
/*
* the default value for the URL string is
* http://www.webyu.com/servlets/webyu/wirelessdevnetsample1
*/
private static String defaultURL =
"http://www.webyu.com/servlets/webyu/wirelessdevnetsample1";
// GUI component for user to enter String
private Display myDisplay = null;
private Form mainScreen;
private TextField requestField;
// GUI component for displaying header information
private Form resultScreen;
private StringItem resultField;
// the "SEND" button used on the mainScreen
Command sendCommand = new Command("SEND", Command.OK, 1);
// the "BACK" button used on the resultScreen
Command backCommand = new Command("BACK", Command.OK, 1);
public Sample1(){
// initializing the GUI components for entering Web URL
myDisplay = Display.getDisplay(this);
mainScreen = new Form("Type in a string:");
requestField =
new TextField(null, "GREAT ARTICLE", 100, TextField.ANY);
mainScreen.append(requestField);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(this);
}
public void startApp() {
myDisplay.setCurrent(mainScreen);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == sendCommand) {
// retrieving the String that user entered
String requeststring = requestField.getString();
// sending a POST request to Web server
String resultstring = sendPostRequest(requeststring);
// displaying the response back from Web server
resultScreen = new Form("Result String:");
resultField = new StringItem(null, resultstring);
resultScreen.append(resultField);
resultScreen.addCommand(backCommand);
resultScreen.setCommandListener(this);
myDisplay.setCurrent(resultScreen);
} else if (c == backCommand) {
// do it all over again
requestField.setString("SOMETHING GOOD");
myDisplay.setCurrent(mainScreen);
}
}
// send a POST request to Web server
public String sendPostRequest(String requeststring) {
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
StringBuffer messagebuffer = new StringBuffer();
try {
// Open up a http connection with the Web server
// for both send and receive operations
hc = (HttpConnection)
Connector.open(defaultURL, Connector.READ_WRITE);
// Set the request method to POST
hc.setRequestMethod(HttpConnection.POST);
// Send the string entered by user byte by byte
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
for (int i = 0; i < request_body.length; i++) {
dos.writeByte(request_body[i]);
}
dos.flush();
dos.close();
// Retrieve the response back from the servlet
dis = new DataInputStream(hc.openInputStream());
int ch;
// Check the Content-Length first
long len = hc.getLength();
if(len!=-1) {
for(int i = 0;i<len;i++)
if((ch = dis.read())!= -1)
messagebuffer.append((char)ch);
} else {
// if the content-length is not available
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
}
dis.close();
} catch (IOException ioe) {
messagebuffer = new StringBuffer("ERROR!");
} finally {
// Free up i/o streams and http connection
try {
if (hc != null) hc.close();
} catch (IOException ignored) {}
try {
if (dis != null) dis.close();
} catch (IOException ignored) {}
try {
if (dos != null) dos.close();
} catch (IOException ignored) {}
}
return messagebuffer.toString();
}
}
No comments:
Post a Comment