开发J2ME联网应用程序
尽管目前的无线网络不够理想,手机联网还是给我们开发人员不小的震撼的。毕竟这真的是件神奇的事情,不是吗?本文将讲述如何应用j2me平台中的通用联网框架开发联网的应用程序。
首先,必须说明一点:midp中规定,任何移动信息设备都必须提供通过http协议的支持,而像其他的通信方式例如socket是设备相关的。有些手机会支持,有些则不支持。这里只大概的说明一下http协议相关的内容,如果不了解这个方面的知识请参考http协议。在javax.microedition.io里面是大量的接口,只有一个connector类,当然在midp2.0里面添加了对push技术的支持,这个留做以后讲。connector类提供的最重要的方法是open()方法,它的返回值为connection,你可以对他进行转换得到你需要的类型,比如我们以http协议访问服务器。
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",
"29 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 ".getbytes());
os.flush(); // optional, getresponsecode will flush
// getting the response code will open the connection,
// 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 an http url");
} finally {
if (is != null)
is.close();
if (os != null)
os.close();
if (c != null)
c.close();
}
}
上面的代码是我取自api doc(建议多读一下api doc)。
下面根据自己的经验说明一下联网中比较重要的问题:
Tag: 联网开发