j2me http联网客户端的编写之一

建立与服务器的连接

 1.采用post方式进行数据传送

   顾名思义,post 方式就是用来向服务器发送数据

  HttpConnection hc = null;
  InputStream is = null;
  String agent = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
  String type = "application/x-www-form-urlencoded";

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;

2.采用get方式进行数据传送

 顾名思义,get方式就是向服务器读取数据

  HttpConnection hc = null;
  InputStream is = null;
  String agent = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
  String type = "application/x-www-form-urlencoded";
  byte result[] = null;
  try {
     hc = (HttpConnection) Connector.open(url + "?" + rawData);//把请求附加到url后面
    hc.setRequestMethod(HttpConnection.GET);
    hc.setRequestProperty("User-Agent", agent);
    hc.setRequestProperty("Content-Language", "en-CA");
    hc.setRequestProperty("Content-Type", type);
    hc.setRequestProperty("Connection", "Keep-Alive");
   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;
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值