在实际的J2ME网络编程中,一般需要提供以CMWAP代理的方式连接网络,在J2ME中,连接的代码和直接连接有所不同,代码如下:
HttpConnection http = (HttpConnection)Connector.open(("http://10.0.0.172/"+url);
http.setRequestProperty("X-Online-Host",ServerName);
例如你需要访问的地址为:
http://www.test.com/login/loginServlet
则上面的代码就为:
HttpConnection http = (HttpConnection)Connector.open((http://10.0.0.172/+”login/loginServlet”);
http.setRequestProperty("X-Online-Host",”www.test.com”);
在实际使用过程中,只需要使用实际需要访问的地址的域名或者IP来代替ServerName,例如示例中的“www.test.com”,使用后续的地址类代替代码中的url,例如示例中的“login/loginServlet”,就可以实际的使用CMWAP代理来进行连接了。
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
在反编译了数个J2ME游戏以及UCSDK之后,发现Http请求都使用到了cmwap代理,而代码几乎同上。
J2ME发起请求,并且获得返回数据:
/**
*
* @param host IP + port 如 125.69.106.132:8099 (不要加http://)
* @param url /sk/payServlet (以/开头)
* @param cmwap 是否使用cmwap接入(是否开启代理)
* @throws IOException
*/
private static void URLRequest(String host, String url, boolean cmwap) throws IOException {
HttpConnection c = null;
InputStream is = null;
int rc;
try {
if (cmwap) {
c = (HttpConnection) Connector.open("http://10.0.0.172:80" + url, 3, true);
c.setRequestProperty("X-Online-Host", host);
c.setRequestProperty("Accept", "*/*");
} else {
c = (HttpConnection) Connector.open("http://" + host + url, 3, true);
}
OutputStream openOutputStream = c.openOutputStream();
openOutputStream.write("Vicky".getBytes());
openOutputStream.flush();
openOutputStream.close();
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();
String type = c.getType();
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;
}
String msg = new String(data,"UTF-8");
System.out.println("MSG>>>>>>>>>>>" + msg);
}
} catch (ClassCastException e) {
throw new IllegalArgumentException("Not an HTTP URL");
} finally {
if (is != null) {
is.close();
}
if (c != null) {
c.close();
}
}
}
Servlet获得请求处理,并返回数据。
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] bufer = new byte[256];
ServletInputStream inputStream = request.getInputStream();
inputStream.read(bufer);
inputStream.close();
String getMsg = new String(bufer,"UTF-8");
System.out.println("getMsg = " + getMsg);
byte[] msg = "Hello World".getBytes();
response.setContentLength(msg.length);
response.setCharacterEncoding("UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(msg);
outputStream.flush();
outputStream.close();
}