虽然你可以通过套接字连接来实现HTTP,但由于如下原因,你应该使用HTTP连接:
> 套接字连接不支持黑莓移动数据系统(MDS)的特色功能,例如推送.
> 使用套接字连接的黑莓设备应用程序通常比使用HTTP连接的黑莓设备应用程序需要更多的带宽
BlackBerry® device applications that use socket connections typically require significantly more bandwidth than BlackBerry device applications that use HTTP connections.
1. 导入如下类:
* net.rim.device.api.system.CoverageInfo
* javax.microedition.io.Connector
* java.lang.String
* java.io.OutputStreamWriter
* java.io.InputStreamReader
2. 导入如下接口:
* net.rim.device.api.system.CoverageStatusListener
* javax.microedition.io.StreamConnection
3. 使用net.rim.device.api.system包中的CoverageInfo类和CoverageStatusListener接口来确认黑莓设备在无线网络覆盖区域内。
4. 调用Connector.open(),指定socket为协议,并将参数deviceside=false附在URL的末端
* 为使用黑莓MDS服务打开套接字连接,将deviceside=false附于URL末端。黑莓设备应用程序必须明确的输入本地主机IP,因为localhost是不被支持的。
private static String URL = "socket://local_machine_IP:4444;deviceside=false";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
* 为通过直接TCP来打开套接字连接,将参数deviceside=true附于URL末端。
private static String URL = "socket://local_machine_IP:4444;deviceside=true";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
* 为通过直接TCP来打开套接字连接,指定APN信息,将参数deviceside=true附于URL末端,并指定将在其之上建立连接的APN。指定链接到APN的用户名和密码(如果APN需要密码)。
private static String URL = "socket:
//local_machine_IP:4444;deviceside=true;apn=internet.com;tunnelauthusername =user165;tunnelauthpassword=user165password";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
5. 使用 openInputStream() 和 openOutputStream() 来发送和接受数据。
OutputStreamWriter _out = new OutputStreamWriter(conn.openOutputStream());
String data = "This is a test";
int length = data.length();
_out.write(data, 0, length);
InputStreamReader _in = new InputStreamReader(conn.openInputStream());
char[] input = new char[length];
for ( int i = 0; i < length; ++i ) {
input[i] = (char)_in.read();
};
6. 在输入流、输出流和套接字连接上调用close()。每个close()都可能抛出IOException。确保黑莓设备应用程序实现了异常处理。
_in.close();
_out.close();
conn.close();