J2ME的通用联网框架
|
|
Author: Wupei | Date: 2009-11-14 |
View: 3121 |
J2ME开发 - 程序设计 | Digg:
6
|
|
用J2ME的通用联网框架开发联网的应用程序尽管目前的无线网络不够理想,手机联网还是给我们开发人员不小的震撼的。毕竟这真的是件神奇的事情,不是吗?本文将讲述如何应用J2ME平台中的通用联网框架开发联网的应用程序。 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\n".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)。 更多阅读: |