Mobile phone networking to developers not a small shock. After all, it's a really magical thing, isn't it? This article will describe how to use the common networking framework in the J2ME platform to develop networked applications.
First, it must be stated that MIDP requires that any Mobile information device must provide support through the HTTP protocol, while other modes of communication, such as socket, are device-related. Some phones will support, others won't. Here is only a general description of the HTTP protocol-related content, if you do not understand this knowledge, please refer to the HTTP protocol. Inside the Javax.microedition.io is a large number of interfaces, only a connector class, of course, added to the midp2.0 inside the support of the push technology, this left to do later. The most important method provided by the connector class is the open () method, whose return value is connection, and you can convert it to the type you need, such as we access the server with the HTTP protocol.
void postviahttpconnection (String url) throws IOException {
Httpconnection c = null;
InputStream is = null;
OutputStream OS = null;
Int RC;
try {
c = (httpconnection) connector.open (URL);
Set the request method and headers
C.setrequestmethod (httpconnection.post);
C.setrequestproperty ("If-modified-since", "Oct 1999 19:43:31 GMT");
C.setrequestproperty ("User-agent", "profile/midp-2.0 configuration/cldc-1.0");
C.setrequestproperty ("Content-language", "en-us");
//Getting the output stream may flush the headers
OS = C.openoutputstream ();
Os.write ("LIST games\n". GetBytes ());
Os.flush ()//Optional, Getresponsecode'll flush
//Getting the response code would open the connection,< br>//Send the request, and read the HTTP response headers.
//The headers are stored until requested.
rc = C.getresponsecode ();
if (RC!= httpconnection.http_ok) {
throw new IOException ("HTTP Response code:" + RC);
}
is = C.openinputstream ();
Get the ContentType
String type = C.gettype ();
Processtype (type);
//Get the length and process the data
int len = (int) c.getlength ();
if (Len > 0) {
int actual = 0;
int bytesread = 0;
byte[] data = new Byte[len];
while (bytesread!= len) && (actual!=-1)) {
actual = Is.read (data, Bytesread, Len-bytesread );
Bytesread + = actual;
}
Process (data);
else {
int ch;
while (ch = is.read ())!=-1) {
process ((byte) ch);
'
}
' catch (classcastexception e) {
throw new IllegalArgumentException ("Not a HTTP URL");
Finally {
if (is!= null)
Is.close ();
if (OS!= null)
Os.close ();
if (c!= null)
C.close ();
}
}