发送XML到服务器
转自:传智播客教程
1.客户端
public static boolean sendXML(String path, String xml)throws Exception{ byte[] data = xml.getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据 conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if(conn.getResponseCode()==200){ return true; } return false; }
2.服务端
public ActionForward getXML(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream inStream = request.getInputStream(); byte[] data = StreamTool.readInputStream(inStream); String xml = new String(data, "UTF-8"); System.out.println(xml); return mapping.findForward("result"); }
3.测试示例:
public void testSendXMLRequest() throws Throwable{ String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><persons><person id=\"23\"><name>liming</name><age>30</age></person></persons>"; HttpRequest.sendXML("http://10.10.97.51:8180/videoweb/video/manage.do?method=getXML", xml); }
浙公网安备 33010602011771号