关于Http Post Xml

本文介绍了一种通过HTTP POST请求发送和接收XML数据的方式,并提供了一个客户端和服务端的Java实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近遇到个项目,登录鉴权部分。

HTTP 消息头的请求行示例:

POST/mms/LoginAuth HTTP/1.1:

  1. <Login_reqReq>  
  2.      <userName>用户名</userName>  
  3.     <pass>密码</pass>  
  4. </Login_reqReq>  
<Login_reqReq>
     <userName>用户名</userName>
    <pass>密码</pass>
</Login_reqReq>

响应的是xml格式的数据信息。


       一开始还真没点头绪,不知道这个xml咋请求的,是不是也写成a.do?userName=用户名&pass=111。

       在网上搜了下资料,自己还真是有点见识浅薄呀~~这个都不知道尴尬


一、概述

在不同的应用之间传递数据,可以通过web service的方法,同时还可以通过Http Post Xml的方法,相比而言,通过web service传递数据灵活,但是配置起来较为麻烦,涉及到新知识的学习,而通过Http Post Xml传递数据,不需要涉及新的知识,但是灵活性稍差,需要客户端和服务端事先约定好xml数据的结构

Http Post Xml方式传递数据在跟移动、联通等电信运营商之间合作时,经常会用到,一般涉及到下面的知识点:

Ø         Java网络编程(java.net包)

Ø         Java IO编程(java.io包)

Ø         文档对象模型(DOM)

Ø         Java解析xml(javax.xml.parsers包)


二、请求实现并处理返回结束(公共模块类)

通过Http Post Xml传递数据,客户端一般是通过URL建立到服务端的连接,向服务端发送xml数据,然后获取服务端的响应并进行解析:

自己写了个公共类BaseServletRequest.java  免得各个地方使用的时候还要又写一次,代码如下

  1. public class BaseServletRequest  
  2. {  
  3.     public static Document doTheProcess(String xmlString, String urlStr)  
  4.     {  
  5.         DataInputStream input = null;  
  6.         java.io.ByteArrayOutputStream out = null;  
  7.         try  
  8.         {  
  9.             byte[] xmlData = xmlString.getBytes();  
  10.             // 获得到位置服务的链接   
  11.             URL url = new URL(urlStr);  
  12.             URLConnection urlCon = url.openConnection();  
  13.             urlCon.setDoOutput(true);  
  14.             urlCon.setDoInput(true);  
  15.             urlCon.setUseCaches(false);  
  16.             // 将xml数据发送到位置服务   
  17.             urlCon.setRequestProperty("Content-Type""text/xml");  
  18.             urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));  
  19.   
  20.             DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());  
  21.             printout.write(xmlData);  
  22.             printout.flush();  
  23.             printout.close();  
  24.             input = new DataInputStream(urlCon.getInputStream());  
  25.             byte[] rResult;  
  26.             out = new java.io.ByteArrayOutputStream();  
  27.             byte[] bufferByte = new byte[256];  
  28.             int l = -1;  
  29.             int downloadSize = 0;  
  30.   
  31.             while ((l = input.read(bufferByte)) > -1)  
  32.             {  
  33.                 downloadSize += l;  
  34.                 out.write(bufferByte, 0, l);  
  35.                 out.flush();  
  36.             }  
  37.             rResult = out.toByteArray();  
  38.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  39.             DocumentBuilder db = dbf.newDocumentBuilder();  
  40.             Document d = db.parse(new ByteArrayInputStream(rResult));  
  41.             return d;  
  42.         }  
  43.         catch (Exception e)  
  44.         {  
  45.             e.printStackTrace();  
  46.         }  
  47.         finally  
  48.         {  
  49.             try  
  50.             {  
  51.                 out.close();  
  52.                 input.close();  
  53.             }  
  54.             catch (Exception ex)  
  55.             {  
  56.                 ex.printStackTrace();  
  57.             }  
  58.         }  
  59.         return null;  
  60.     }  
  61. }  
public class BaseServletRequest
{
	public static Document doTheProcess(String xmlString, String urlStr)
	{
		DataInputStream input = null;
		java.io.ByteArrayOutputStream out = null;
		try
		{
			byte[] xmlData = xmlString.getBytes();
			// 获得到位置服务的链接
			URL url = new URL(urlStr);
			URLConnection urlCon = url.openConnection();
			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			urlCon.setUseCaches(false);
			// 将xml数据发送到位置服务
			urlCon.setRequestProperty("Content-Type", "text/xml");
			urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));

			DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
			printout.write(xmlData);
			printout.flush();
			printout.close();
			input = new DataInputStream(urlCon.getInputStream());
			byte[] rResult;
			out = new java.io.ByteArrayOutputStream();
			byte[] bufferByte = new byte[256];
			int l = -1;
			int downloadSize = 0;

			while ((l = input.read(bufferByte)) > -1)
			{
				downloadSize += l;
				out.write(bufferByte, 0, l);
				out.flush();
			}
			rResult = out.toByteArray();
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document d = db.parse(new ByteArrayInputStream(rResult));
			return d;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				out.close();
				input.close();
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		return null;
	}
}

       三、客户端的实现,调用了刚才公共类的处理 ClientDemo.java

  1. public class ClientDemo  
  2. {  
  3.     public static void main(String[] args)  
  4.     {  
  5.         String xmlString = "<?xml version='1.0' encoding='gb2312'?><Req><EventContentReq>"  
  6.                 + "<EventID>101</EventID></EventContentReq></Req>";  
  7.         String urlStr = "http://localhost:8080/Foster_Blog/HttpRequestDemo";  
  8.   
  9.                 // 调用参数传递,返回一个document,要什么值再直接从中去取。   
  10.         Document d = BaseServletRequest.doTheProcess(xmlString, urlStr);  
  11.         String TaskAddr = d.getElementsByTagName("TaskAddr").item(0).getFirstChild().getNodeValue();  
  12.         System.out.println("TaskAddr:" + TaskAddr);  
  13.     }  
  14. }  
public class ClientDemo
{
	public static void main(String[] args)
	{
		String xmlString = "<?xml version='1.0' encoding='gb2312'?><Req><EventContentReq>"
				+ "<EventID>101</EventID></EventContentReq></Req>";
		String urlStr = "http://localhost:8080/Foster_Blog/HttpRequestDemo";

                // 调用参数传递,返回一个document,要什么值再直接从中去取。
		Document d = BaseServletRequest.doTheProcess(xmlString, urlStr);
		String TaskAddr = d.getElementsByTagName("TaskAddr").item(0).getFirstChild().getNodeValue();
		System.out.println("TaskAddr:" + TaskAddr);
	}
}


四、服务器端代码

  1. protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,  
  2.             IOException  
  3.     {  
  4.         try{    
  5.             //解析对方发来的xml数据,获得EventID节点的值     
  6.                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    
  7.                    DocumentBuilder db = dbf.newDocumentBuilder();    
  8.                    Document d = db.parse(request.getInputStream());    
  9.                        // 请求时传递的哪些值,需要的就取出来。。   
  10.                    String evtid = d.getElementsByTagName("EventID").item(0).getFirstChild().getNodeValue();    
  11.                    System.out.println("evtid" + evtid);    
  12.                 
  13.                    //根据evtid查找任务,生成xml字符串(格式要正确。。)       
  14.                    String xmlString = "<Req>" + "<EventContentReq>"  
  15.                     + "<TaskAddr> U should study.....</TaskAddr >" + "</EventContentReq>" + "</Req>";   
  16.                    System.out.println("returned xmlString:" + xmlString);    
  17.                 
  18.                    //把xml字符串写入响应     
  19.                    byte[] xmlData = xmlString.getBytes();    
  20.                    response.setContentType("text/xml");    
  21.                    response.setContentLength(xmlData.length);    
  22.                    ServletOutputStream os = response.getOutputStream();    
  23.                    os.write(xmlData);    
  24.                    os.flush();    
  25.                    os.close();    
  26.             }    
  27.             catch(Exception e){    
  28.                    e.printStackTrace();    
  29.             }    
  30.     }  
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException
	{
	    try{  
	        //解析对方发来的xml数据,获得EventID节点的值  
	               DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
	               DocumentBuilder db = dbf.newDocumentBuilder();  
	               Document d = db.parse(request.getInputStream());  
                       // 请求时传递的哪些值,需要的就取出来。。
	               String evtid = d.getElementsByTagName("EventID").item(0).getFirstChild().getNodeValue();  
	               System.out.println("evtid" + evtid);  
	          
	               //根据evtid查找任务,生成xml字符串(格式要正确。。)    
	               String xmlString = "<Req>" + "<EventContentReq>"
					+ "<TaskAddr> U should study.....</TaskAddr >" + "</EventContentReq>" + "</Req>"; 
	               System.out.println("returned xmlString:" + xmlString);  
	          
	               //把xml字符串写入响应  
	               byte[] xmlData = xmlString.getBytes();  
	               response.setContentType("text/xml");  
	               response.setContentLength(xmlData.length);  
	               ServletOutputStream os = response.getOutputStream();  
	               os.write(xmlData);  
	               os.flush();  
	               os.close();  
	        }  
	        catch(Exception e){  
	               e.printStackTrace();  
	        }  
	}

          至此,功能结束。    总结一下请求有以下几种方式:  ajax直接请求,或者servlet, action等, 其实都是等效的。还有web Service,这个还要弄客户端,服务端等比较麻烦点。 再一个呢 就是现在的Http Post Xml数据请求了。  My pleasure to share this article for all.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值