如何POST多个xml到WebService
本文关键字:WebService xml 多个 POST 如何 | 更新日期: 2023-09-27 18:11:53
实际上我有代码在c#做一个httpwebrequest与POST方法发送一个XML和接收一个XML答案并保存它,这里是代码:
public static XmlDocument PostXMLTransaction(string v_strURL)
{
//Declare XMLResponse document
XmlDocument XMLResponse = null;
//Declare an HTTP-specific implementation of the WebRequest class.
HttpWebRequest objHttpWebRequest;
//Declare an HTTP-specific implementation of the WebResponse class
HttpWebResponse objHttpWebResponse = null;
//Declare a generic view of a sequence of bytes
Stream objRequestStream = null;
Stream objResponseStream = null;
//Declare XMLReader
XmlTextReader objXMLReader;
//Creates an HttpWebRequest for the specified URL.
objHttpWebRequest = (HttpWebRequest)WebRequest.Create(v_strURL);
try
{
//---------- Start HttpRequest
//Set HttpWebRequest properties
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes("C:''Documents' 'Aplicacion1''Aplicacion1''absisSIHttpProfileTO.xm l");
objHttpWebRequest.Method = "POST";
objHttpWebRequest.ContentLength = bytes.Length;
objHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
//Get Stream object
objRequestStream = objHttpWebRequest.GetRequestStream();
//Writes a sequence of bytes to the current stream
objRequestStream.Write(bytes, 0, bytes.Length);
//Close stream
objRequestStream.Close();
//---------- End HttpRequest
//Sends the HttpWebRequest, and waits for a response.
objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();
//---------- Start HttpResponse
if (objHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
//Get response stream
objResponseStream = objHttpWebResponse.GetResponseStream();
//Load response stream into XMLReader
objXMLReader = new XmlTextReader(objResponseStream);
//Declare XMLDocument
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(objXMLReader);
xmldoc.Save(@"C:'Documents'Aplicacion1'Aplicacion1'myxml.xml");
//Set XMLResponse object returned from XMLReader
XMLResponse = xmldoc;
//Close XMLReader
objXMLReader.Close();
}
//Close HttpWebResponse
objHttpWebResponse.Close();
}
catch (WebException we)
{
//TODO: Add custom exception handling
throw new Exception(we.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
//Close connections
objRequestStream.Close();
objResponseStream.Close();
objHttpWebResponse.Close();
//Release objects
objXMLReader = null;
objRequestStream = null;
objResponseStream = null;
objHttpWebResponse = null;
objHttpWebRequest = null;
}
//Return
return XMLResponse;
}
现在我的问题是我如何发送多个XML作为参数在一个httpwebrequest?
:XmlDocument xml1, XmlDocument xml2)
这取决于你的协议。另一端的服务器需要知道如何在一个连接上处理多个消息。如果服务器是http web服务器,那么您很幸运,因为该协议已经定义了重用连接的机制。(尽管客户端和服务器都必须同意使用这个)。
为此,您可以使用HttpWebRequest的KeepAlive属性,参见:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx