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

Android之通过HTTP协议向服务器发送XML数据

2013-05-06 13:04 375 查看
可以通过装载或读取一个XML文件,得到其数据,然后把得到的数据当成实体,通过HTTP协议用输出流发送给服务器,在服务器端通过获取输入流获取相关数据,这样就是实现了向服务器发送XML数据。如下:


客户端:


public void sendXmlTest() throws Exception{
//通过类装载器装载XML资源
InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("test.xml");
byte[] xml=StreamTool.read(inputStream);

String path="http://172.22.35.112:8080/videonews/GetXmlInfo";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);

//设置HTTP请求的头字段
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); //内容类型
conn.setRequestProperty("Content-Length", String.valueOf(xml.length)); //实体内容的长度

conn.getOutputStream().write(xml); //通过输出流把数据写到服务器
if(conn.getResponseCode()==200){
System.out.println("发送成功!");
}else{
System.out.println("发送失败!");
}
}


服务器端:

byte[] xml=StreamTool.read(request.getInputStream()); //获得输出流

System.out.println(new String(xml,"UTF-8"));

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