您的位置:首页 > 理论基础 > 计算机网络

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

2006-08-17 10:49 309 查看
建立与服务器的连接
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: