首页 >后端开发 >C#.Net教程 >C#中关于Send WebRequest 方法和数据处理

C#中关于Send WebRequest 方法和数据处理

巴扎黑
巴扎黑原创
2016-12-19 16:27:021485浏览

   很久不更新博客了,这次大概说一下C#中的Send WebRequest,众所周知,.NET网络编程在测试中是非常常见的,具体来说,比如我们如果测试一个API,通过Send WebRequest的方式来进行API层面的功能测试,然后用Selenium完成前端的验证,这种模式应该说是比较方便而通用的,具体以其中最常见的HTTP request为例,当我们需要传输数据时,需要 
1)地址:Address作为Webrequest参数实例化,然后设定相应属性,比如Method(Get还是Post等等) 
2)数据:Data作为HttpRequest的数据流写入: 

XmlResponse = null; 
ResponseCode = HttpStatusCode.Unused; 
ServerResponse = String.Empty; 

参数处理部分 
//Format the data 
string output = data.Aggregate(String.Empty, (current, keyValuePair) => current + ("&" + keyValuePair.Key + "=" + HttpUtility.UrlEncode(keyValuePair.Value))); 
var encoding = new UTF8Encoding(); 
//设置PostData变量将output进行处理,最终得到byte[] d作为最终数据写入到WebRequest中 
var Postdata = Encoding.ASCII.GetBytes(output); 
                byte[] d = encoding.GetBytes(output.Substring(1, output.Length - 1)); 

var address = TargetUrl; 
//GET部分的数据处理 
if (method.ToUpperInvariant() == "GET") 
                    address=address+output; 

//POST部分的数据处理 
WebRequest request = WebRequest.Create(address) as HttpWebRequest; 
//Add post process 
if (request == null) 
  throw new Exception("WebRequest object is null."); 

request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = d.Length; 

ServerResponse = String.Empty; 

//数据读取及处理部分 
using (Stream dataStream = request.GetRequestStream()) 
  { 
     dataStream.Write(d, 0, d.Length); 
     dataStream.Close(); 

     using (var response = (HttpWebResponse)request.GetResponse()) 
        { 
          ResponseCode = response.StatusCode; 
          using (Stream myStream = response.GetResponseStream()) 
            { 
               if (myStream != null) 
                            { 
                                var readStream = new StreamReader(myStream, Encoding.UTF8); 
                                ServerResponse = readStream.ReadToEnd(); 
                            } 
                        } 
                        response.Close(); 
            } 
         } 


                if (ResponseCode == HttpStatusCode.OK) 
                { 
                    if (loadXml) 
                        LoadXml(); 
                    return true; 
                } 
                    
                return false;

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn