你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
用J2ME的通用联网框架开发联网应用程序(1)
 
手机联网给开发人员不小的震撼的。毕竟这真的是件神奇的事情,不是吗?本文将讲述如何应用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();
  }
}

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089