#region 发送xml文件给指定网址
/// <summary>
/// 发送xml文件给指定网址
/// </summary>
/// <param name="v_strURL">目标Url</param>
/// <param name="v_objXMLDoc">需要发送的数据(XmlDocument格式的)</param>
/// <returns>服务器响应</returns>
public static XmlDocument PostXMLTransaction(string v_strURL, XmlDocument v_objXMLDoc)
{
//set max enough to avoid http request is used out -> avoid dead while get response
ServicePointManager.DefaultConnectionLimit = 200;
XmlDocument XmlResponse = null;
HttpWebRequest req;
HttpWebResponse rep = null;
Stream reqStream = null;
//创建一个流对象(用来读取响应对象的内容)
Stream repStream = null;
XmlTextReader objXmlReader;
//垃圾回收
System.GC.Collect();
req = (HttpWebRequest)WebRequest.Create(v_strURL);
try
{
# region Start HttpRequest
byte[] bytes;
//传递的值
bytes = Encoding.UTF8.GetBytes(v_objXMLDoc.InnerXml);
//传递的方法,必须要写,而已Get必须大写。
req.Method = "POST";
req.ContentLength = bytes.Length;
//表头的格式必须要写,否则请求响应的页面得不到要传递的值
req.ContentType = "text/xml;encoding='utf-8'";
//把传递的值写到流中
reqStream = req.GetRequestStream();
reqStream.Write(bytes,0,bytes.Length);
//必须要关闭请求
reqStream.Close();
#endregion End HttpRequest
//创建一个响应对象,并从请求对象中得到响应对象的事例。
rep = (HttpWebResponse)req.GetResponse();//此时程序才开始向目标网页发送Post请求
//rep = req.GetResponse() as HttpWebResponse;
#region Start HttpResponse
//HttpStatusCode.OK,指示请求成功,且请求的信息包含在响应中
if (rep.StatusCode == HttpStatusCode.OK)
{
//得到回应过来的流
repStream = rep.GetResponseStream();
//Load response stream into XMLReader
objXmlReader = new XmlTextReader(repStream);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(objXmlReader);
XmlResponse = xmldoc;
objXmlReader.Close();
}
//响应关闭,要不会占用网络资源
rep.Close();
#endregion
}
catch (WebException we)
{
//异常处理
}
catch (Exception ex)
{
//异常处理
}
finally
{
//关闭连接
reqStream.Close();
repStream.Close();
rep.Close();
//释放对象
objXmlReader = null;
reqStream = null;
repStream = null;
rep = null;
//objHttpWebRequest = null;
if (req!= null)
{
req.Abort();
}
}
return XmlResponse;
}
#endregion
小注:
1、
Content-Type:很多时候无法解析就是Content-Type的问题。如果本身就是xml文件,请跳过这一步
动态生成的XML一定要将其设置为text/xml,否则默认就是text/html也就是普通的文本了。
2、
HttpWebRequest在初始化的时候要先根据url进行创建,然后再设置Method和ContentType,然后再将请求的内容写进去,通过GetRequestStream来返回流,再向这个流中写请求内容便可以了。再通过request对象的GetResponse方法返回response对象,最后得到返回的数据流,这是通过GetResponseStream方法返回的,最后从这个流中读出返回的数据便ok了。
3、ServicePointManager
.DefaultConnectionLimit Property:Gets or sets the maximum number of concurrent connections allowed by a ServicePoint object.
C#中的AS、IS运算符与强制类型转换
<wbr><br></wbr>
<wbr><br></wbr>