您的位置:首页 > 其它

J2ME通过URL访问XML文件并下载XML到本地

2010-06-29 20:13 295 查看
(叶全府)J2ME通过URL访问XML文件并下载XML到本地
2009-06-11 14:45
**
* 网络连接
* 固定URL的网络连接
* @param cmnet
* true走cmnet false走cmwap
* @return返回String类型的XML数据
*/
private String connect(boolean cmnet) {

try {
if (cmnet) {

http = (HttpConnection) Connector
.open(http://xx.cn/t.xml);

} else {
http = (HttpConnection) Connector
.open(http://10.0.0.3/t.xml);
http.setRequestProperty("X-Online-Host", "xx.cn");
}

http.setRequestProperty("Content-Type", "application/octet-stream");
http.setRequestProperty("Connection", "Keep-Alive");
http.setRequestMethod(HttpConnection.GET);

// 判断是否为连接网络收费提示页面
String content_type = http.getHeaderField("Content-Type");
// 如果是返回移动的拦截页面,则重发.
if (content_type.indexOf("wml") != -1) {
try {
http.close();
} catch (IOException e) {
}
http = null;
// 重新发起一次请求

if (cmnet) {
http = (HttpConnection) Connector
.open(http://xx.cn/t.xml);
} else {
http = (HttpConnection) Connector
.open(http://10.0.0.3/t.xml);
http.setRequestProperty("X-Online-Host",
"xx.cn");
}
http.setRequestMethod(HttpConnection.GET);

}
int code = http.getResponseCode();

if (code == 200) {// 返回200 表示连接成功

// 打开输入流,读取数据
InputStreamReader is = new InputStreamReader(http
.openInputStream(), "UTF-8");
// 建一StringBuffer,用于保存已读的数据
StringBuffer sb = new StringBuffer();
// 每次读取1K的数据
char[] c = new char[1024];
int k;
// 循环读取数据,直到读完 当返回-1时表示流已读完
while ((k = is.read(c)) != -1) {
sb.append(c, 0, k);
}

is.close();
is = null;
http.close();
http = null;
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
// return null;
} finally {

if (http != null) {
try {
http.close();
http = null;
} catch (IOException e) {
}
http = null;
}
}

return null;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐