本文執行個體講述了Android發送xml資料給伺服器的方法。分享給大家供大家參考。具體如下:
一、發送xml資料:
public static void main(String[] args) throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><videos><video><title>中國</title></video></videos>"; String path = http://localhost:8083/videoweb/video/manage.do?method=getXML ; byte[] entity = xml.getBytes("UTF-8"); HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true); //指定發送的內容類型為xml conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(entity); if(conn.getResponseCode() == 200){ System.out.println("發送成功"); }else{ System.out.println("發送失敗"); }}
二、接受xml資料:
public ActionForward getXML(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream inStream = request.getInputStream(); byte[] data = StreamTool.read(inStream); String xml = new String(data, "UTF-8"); System.out.println(xml); return mapping.findForward("result");}
希望本文所述對大家的Android程式設計有所協助。