可以通過裝載或讀取一個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"));