j2me http联网客户端编写之二

来源:互联网 发布:防地雷反伏击车数据 编辑:程序博客网 时间:2024/04/29 04:37

 接收和发送大量数据

     受限于手机的连网性能,我们无法实现一次性的发送大量数据(如图片的发送和接收),因此必须实现数据的分段接收和发送.

例子:

   客户端采用http,服务器用php编写

   1.接收数据

    涉及到服务器和客户端的编码方式问题,若只传送字节流,不做任何的编解码操作,则可有效的避免这一问题.一次接收数据的流程:

    客户端发送读取数据请求-->服务器返回数据的段数-->客户端读取第一段-->客户端读取第二段......-->读取完成,客户端处理数据.

    2.发送数据

发送数据的流程正好跟接收数据相反.

发送数据时采用post,模拟pc上上传文件的方法

一次发送代码

 

  HttpConnection hc = null;
  InputStream is = null;
  String agent = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
  String   type = "multipart/form-data;" + "boundary=" + BOUNDARY;  //模拟form 发送

  byte result[] = null;
  try {
    hc = (HttpConnection) Connector.open(url);
    hc.setRequestMethod(HttpConnection.POST);
    hc.setRequestProperty("User-Agent", agent);
    hc.setRequestProperty("Content-Type", type);
    hc.setRequestProperty("Content-Length", new Integer(rawData.length()).toString());
    OutputStream os = hc.openOutputStream();
    os.write(rawData.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
   is = hc.openDataInputStream();
   int ch;
   while ((ch = is.read()) != -1) {
    baos.write(ch);
   }
   result = baos.toByteArray();
   baos.close();
  } catch (Exception e) {
   e.printStackTrace();
   result = null;
   throw e;
  } finally {
   try {
    if (is != null) {
     is.close();
     is = null;
    }
    if (hc != null) {
     hc.close();
     hc = null;
    }
   } catch (Exception e) {
    e.printStackTrace();
    result = null;
    throw e;
   }
  }
  return result;

rawdata 为发送的数据,其组成方式为

分隔符号

项目

分隔符号

项目

分隔符号

.

.

.

.

分隔符号可随机生成,每一项用分隔符号分隔,用户可任意向里面添加项目.

--7d4a6d158c9

Content-Disposition: form-data; name="offset" //此次传送的数据在整个文件中的下标

 

6144

--7d4a6d158c9

Content-Disposition: form-data; name="length"//此次传送的数据长度

 

444

--7d4a6d158c9

Content-Disposition: form-data; name="total"   //总的数据长度

 

6588

--7d4a6d158c9

Content-Disposition: form-data; name="format"

 

jpg

--7d4a6d158c9

Content-Disposition: form-data; name="file"; filename="camare.jpg"   //文件名可任意写

 

鯻q}魁碩08]t刊檍?x凗侜W??     //发送的数据段

--7d4a6d158c9--