android发送xml信息到web服务器简单例子
android:
发送以下内容形式的xml文件,
<?xml version="1.0" encoding="utf-8"?>
<userinf>
<username>test</username>
<password>123</password>
</userinf>
1、直接发送
String xml = "<userinf><username>test</username><password>123</password></userinf>";
这个String字符串也是可以的!我试过.
2、
使用InputStream in = this.getClass().getClassLoader().
getResourceAsStream(“userinfo.xml”);方法
使用这个类的装载器进行加载xml文件到输入流,然后在把输入流中信息读取出来,再发送给服务器就行!
发送xml信息的http请求:
public static boolean sendData(String path, byte[] data){
//传入路径和要输出的内容
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");//设置发送方式
conn.setDoOutput(true);//设置输出
conn.setReadTimeout(3000);
conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");//这里要设置请求头!"text/xml"这个要设置好
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outs= conn.getOutputStream();
outs.write(data);
if(conn.getResponseCode==200){
//如果不执行这一步,那么内容就只是写到内存里,没有发送出去
//发送成功
}
}
服务器:
接收xml信息:
//在servlet中操作
1、获取输入流,
servlet中的doPost(HttpServletRequest request, HttpServletResponse response)方法内:
request.getInputStream();//拿到输入流,解析文件
2、从xml输入流中解析信息:(使用Dom解析)
public void parseXML(InputStream in) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//得到文件对象工厂
DocumentBuilder db = dbf.newDocumentBuilder();//创建一个文件对象
Document doc = db.parse(in);//从xml输入流得到一个文档对象,以下的操作都是建立在这个文档对象上的
//文档对象是一个树形结构的
//得到根节点
Element root = doc.getDocumentElement();//拿到根节点
System.out.println(root.getNodeName());
if(root == null) return;
NodeList userlist = root.getChildNodes();//拿到根节点的子节点,第一层
if(userlist!=null){
getNodeContent(userlist);
}
}
public void getNodeContent(NodeList childNodes){//这里做了一个简单的解析用户名和密码的功能
for (int i = 0; i < childNodes.getLength(); i++)//遍历根节点的子节点
{
Node item = childNodes.item(i);
if( item.getNodeType()==Node.ELEMENT_NODE){//判断是否是节点
if("username".equals(item.getNodeName()))//判断节点的名字
{
String username = item.getTextContent()); //拿到子节点的文本内容
}
if("password".equals(item.getNodeName()))
{
String password = item.getTextContent());
}
NodeList secondNodes = item.getChildNodes();//拿到该节点的下一层所有子节点
if(secondNodes != null){
getNodeContent(secondNodes); //递归进行
}
}
}
3、解析完成后即可对参数进行相关操作
服务器发送xml文件信息也可以像android发送到web同样这样做!
用输出流输出到android端即可,然后android再进行解析即可。
android使用pull解析,也可以用其他解析