android学习之 向网络中发送 XML格式数据
客户端:android
步骤1 先对一个xml进行数据解析为字节数组(byte[]) 然后再通过HttpURLConnection 进行配置发送 关键代码如下
byte[] data=NetWorkTool.getUrlData(将要解析的url路径); HttpURLConnection conn=(HttpURLConnection) new URL("将要请求的url路径").openConnection(); conn.setConnectTimeout(5000); // 设置连接超时时间 conn.setRequestMethod("POST"); // 设置请求方式 conn.setDoOutput(true); //设置允许发送数据 conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); //设置内容类型 conn.setRequestProperty("Content-Length", String.valueOf(data.length)); //数据长度 conn.getOutputStream().write(data); //写入数据到缓冲区 if(conn.getResponseCode() == 200){ // 这里才是真正发送数据 System.out.println("发送成功"); }else{ System.out.println("发送失败"); }
服务端解析传递过来的xml数据 :servlet
InputStream input=req.getInputStream(); byte[] data=StreamTool.read(input); String str=new String(data,"UTF-8"); System.out.println(str);