C#中使用POST发送XML2014-10-07说明:返回string中可能出现中文乱码问题
<span style="white-space: pre;"></span>/// <summary>/// C#POST 发送XML/// </summary>/// <param name="url">目标Url</param>/// <param name="strPost">要Post的字符串(数据)</param>/// <returns>服务器响应</returns>private string PostXml(string url, string strPost){string result = string.Empty;//Our postvars//ASCIIEncoding.ASCII.GetBytes(string str)//就是把字符串str按照简体中文(ASCIIEncoding.ASCII)的编码方式,//编码成 Bytes类型的字节流数组; // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式,如果没有注意对应会出现文末的错误byte[] buffer = Encoding.UTF8.GetBytes(strPost);StreamWriter myWriter = null;//根据url创建HttpWebRequest对象//Initialisation, we use localhost, change if appliableHttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);//Our method is post, otherwise the buffer (postvars) would be uselessobjRequest.Method = "POST";//The length of the buffer (postvars) is used as contentlength.//Set the content length of the string being posted.objRequest.ContentLength = buffer.Length;//We use form contentType, for the postvars.//Set the content type of the data being posted.objRequest.ContentType = "text/xml";//提交xml //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单try{//We open a stream for writing the postvarsmyWriter = new StreamWriter(objRequest.GetRequestStream());//Now we write, and afterwards, we close. Closing is always important!myWriter.Write(strPost);}catch (Exception e){return e.Message;}finally{myWriter.Close();}//读取服务器返回信息//Get the response handle, we have no true response yet!//本文URL:http://www.bianceng.cn/Programming/csharp/201410/45576.htmHttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();//using作为语句,用于定义一个范围,在此范围的末尾将释放对象using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())){//ReadToEnd适用于小文件的读取,一次性的返回整个文件result = sr.ReadToEnd();sr.Close();}return result;}
背景:我发送的是encoding="UTF-8"格式的xml字符串,但一开始我使用的是Encoding.Unicode.GetBytes(strPost)或者Default、ASCII均会提示错误。修改字符编码格式后,成功!所以要根据发送的格式选取合适的方法。注意:该函数可以发送xml到用友那边,但返回信息中中文字符为乱码。这个函数也可以实现同样的功能却避免了乱码问题详细过程及代码如下:1、创建httpWebRequest对象,HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。 WebRequest是获得一些应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。2、初始化HttpWebRequest对象,这个过程提供一些http请求常用的标头属性:agentstring,contenttype等,其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。很多认真设计的网站都会根据这个值来返回对不同浏览器特别优化的代码。3、附加要POST给服务器的数据到HttpWebRequest对象,附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。4、读取服务器的返回信息,读取服务器返回的时候,要注意返回数据的encoding,如果我们提供的解码类型不对,会造成乱码,比较常见的是utf-8和gb2312。通常,网站会把它编码的方式放在http header里面,如果没有,我们只能通过对返回二进制值的统计方法来确定它的编码方式。