android客户端发送XML数据至服务器

使用android发送XML数据

服务器端:

1.用一个servlet来接收android客户端的请求。

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kafei.utils.StreamTool;

@WebServlet("/XmlServlet")
public class XmlServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//通过request的getInputStream方法可以获得android客户端发送的XML数据流
		byte[] data = StreamTool.read(request.getInputStream());
		String xml = new String(data, "UTF-8");
		System.out.println(xml);
	}
}
2.读取流中的数据:

/**
	 * 读取流中的数据
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		byte[] b=new byte[1024];
		int len=0;
		while((len=inputStream.read(b))!=-1){
			outputStream.write(b,0,len);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
android客户端:

1.首先准备一个提供测试的XML文件(city.xml),放在src目录下:

<?xml version="1.0" encoding="UTF-8"?>
<citys>
  <china id="0">
    <city>兰州</city>
    <province>甘肃</province>
  </china>
  <china id="1">
    <city>庆阳</city>
    <province>甘肃</province>
  </china>  
</citys>
2.编写发送的业务逻辑:

public void testSendXML() throws Exception {
		// 向服务器发送实体数据
		InputStream inStream = this.getClass().getClassLoader()
				.getResourceAsStream("city.xml");//加载本地XML文件
		byte[] data = StreamTool.read(inStream);//获得文件的字节数组
		String path = "http://192.168.1.100:8080/web/XmlServlet";//发送路径
		HttpURLConnection conn = (HttpURLConnection) new URL(path)
				.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");//以PSOT方式进行提交
		conn.setDoOutput(true);//允许输出数据
		conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");//设置发送的文件类型
		conn.setRequestProperty("Content-Length", String.valueOf(data.length));//设置发送文件的长度
		conn.getOutputStream().write(data);//些人输出流中
		//判断是否发送成功,只有调用了getResponseCode方法才真正的实现发送的动作
		if (conn.getResponseCode() == 200) {
			System.out.println("发送成功");
		} else {
			System.out.println("发送失败");
		}
	}
至此android客户端向服务器发送XML数据就已完成。欢迎大家进行交流

你可能感兴趣的:(android客户端发送XML数据至服务器)