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

通过Http协议发送XML数据

2013-07-04 14:26 330 查看
public class SendXmlTest {

public static void main(String[] args) throws Throwable {

//在src下面创建person.xml 这样可以用类加载器来获取输入流
   InputStream inputStream=SendXmlTest.class.getClassLoader().getResourceAsStream("person.xml");
   byte[] data=StreamTool.readInStream(inputStream);//使用工具类 StreamTool中的方法 readStream()读取输入流

   String path="http://192.168.8.103:8080/VideoWeb/manage.do?method=getXML";

   URL url=new URL(path);

   HttpURLConnection conn=(HttpURLConnection)url.openConnection();//1打开连接
   conn.setConnectTimeout(5*1000);// 2 设置浏览器反应最长时间
   conn.setDoOutput(true);//3 如果是用post方法 需要设置为true
   conn.setRequestMethod("POST"); // 4 设置传递内容的方法 post或者 Get

// 5 设置头文件
   conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
   conn.setRequestProperty("Content-Length", String.valueOf(data.length));
   OutputStream out=conn.getOutputStream();// 6 获得一个输出流对象
   out.write(data);// 7 将数据提交给服务器端
   out.flush();
   if(conn.getResponseCode()==200){
    byte[] result = StreamTool.readInStream(conn.getInputStream());
   }
   out.close();
}
  

}

//工具类:读取输入流 将输入流转换为字节数组

public class StreamTool {

public static byte[] readInStream(InputStream inputStream)throws Throwable {

   byte [] buffer=new byte[1024];

   int len=0;

   ByteArrayOutputStream outStream=new ByteArrayOutputStream();

   while((len=inputStream.read(buffer))!=-1){

    outStream.write(buffer, 0, len);

   }

   inputStream.close();

   outStream.close();

   return outStream.toByteArray();

}

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