Android之通過HTTP協議向伺服器發送XML資料

來源:互聯網
上載者:User
       可以通過裝載或讀取一個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("發送失敗!");
}
}

  
伺服器端:
  1. byte[] xml=StreamTool.read(request.getInputStream());  //獲得輸出資料流
  2. System.out.println(new String(xml,"UTF-8"));
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.