Web运行原理简单地说是“浏览器发送一个HTTP Request到Web服务器上,Web服务器处理完后将结果(HTTP Response)返回给浏览器”。
通常测试一个web api是否正确,可以通过自己coding方式模拟向Web服务器发送Http Request(设置好各参数),然后再通过捕获Web服务器返回的Http Response并将其进行解析,验证它是否与预期的结果一致。
.net中提供的Http相关的类
主要是在命名空间System.Net里,提供了以下几种类处理方式:
WebClient
WebRequest WebResponse
HttpWebRequest HttpWebResponse
TcpClient
Socket
(1)使用WebRequest 获取指定URL的内容测试code
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Net; 8 9 namespace Testing0110 {11 class WebRequestTest12 {13 static void Main(string[] args)14 {15 string url = @"http://www.baidu.com";16 //string html = TestWebClient(url);17 //string html = TestWebRequest(url); 18 string html = TestHttpWebRequest(url); 19 Console.WriteLine(html);20 Console.Read();21 }22 23 ///24 /// 使用WebClient发出http request25 /// 26 /// 27 ///28 public static string TestWebClient(string url)29 {30 Console.WriteLine("Testing WebClient......");31 WebClient wc = new WebClient(); 32 Stream stream = wc.OpenRead(url);33 string result = "";34 using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))35 {36 result = sr.ReadToEnd();37 }38 return result;39 40 }41 42 /// 43 /// 使用WebClient发出http request44 /// 45 /// 46 ///47 public static string TestWebRequest(string url)48 {49 Console.WriteLine("Testing WebRequest......");50 WebRequest wr = WebRequest.Create(url);51 wr.Method = "GET";52 WebResponse response = wr.GetResponse();53 Stream stream = response.GetResponseStream();54 string result = "";55 using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))56 {57 result = sr.ReadToEnd();58 }59 return result;60 }61 62 /// 63 /// 使用HttpWebClient发出http request64 /// 65 /// 66 ///67 public static string TestHttpWebRequest(string url)68 {69 Console.WriteLine("Testing HttpWebRequest......");70 HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);71 wr.Method = "GET";72 HttpWebResponse response = (HttpWebResponse)wr.GetResponse();73 Stream stream = response.GetResponseStream();74 string result = "";75 using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))76 {77 result = sr.ReadToEnd();78 }79 return result;80 }81 }82 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Net; 8 9 namespace Testing0110 {11 class TestHttpWebRequestWithCookie12 {13 static void Main(string[] args) 14 {15 string url = "https://passport.xxx.com/account/login";16 CookieContainer myCookieContainer = new CookieContainer();17 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);18 request.CookieContainer = myCookieContainer;19 string postdata = "bkurl=&LoginName=abc&Password=123456&RememberMe=false";20 request.Method = "POST";21 request.KeepAlive = true;22 byte[] postdata_byte = Encoding.UTF8.GetBytes(postdata);23 request.ContentType = "application/x-www-form-urlencoded";24 request.ContentLength = postdata_byte.Length;25 26 Stream stream = request.GetRequestStream();27 stream.Write(postdata_byte, 0, postdata_byte.Length);28 stream.Close();29 30 HttpWebResponse response = (HttpWebResponse)request.GetResponse();31 StreamReader srRes = new StreamReader(response.GetResponseStream(),Encoding.UTF8);32 string content = srRes.ReadToEnd();33 response.Close();34 srRes.Close();35 36 string cookieString = request.CookieContainer.GetCookieHeader(new Uri(url));37 Console.WriteLine("***********第一次cookie内容:" + cookieString);38 39 request = (HttpWebRequest)WebRequest.Create("http://my.xxx.com/xxx/xxx_list.asp");40 request.Method = "GET";41 request.CookieContainer = myCookieContainer;42 request.Headers.Add("Cookie:" + cookieString);43 request.KeepAlive = true;44 response = (HttpWebResponse)request.GetResponse();45 //cookieString = request.CookieContainer.GetCookieHeader(request.RequestUri) + ";" + cookieString;46 // Console.WriteLine("***********第二次cookie内容:" + cookieString);47 StreamReader srR = new StreamReader(response.GetResponseStream(), Encoding.UTF8);48 string result = srR.ReadToEnd();49 srR.Close();50 Console.WriteLine("**************result:" + result.Substring(500));51 Console.Read();52 }53 }54 }
我们用浏览器打开HTTPS的网站,如果我们没有安装证书,通常页面会显示 "此网站的安全证书有问题",我们必须再次点"继续浏览此网站(不推荐)"才能查看页面信息.
如下图所示
那么我们的程序,如何忽略HTTPS证书错误呢?
只要在程序中加入下面这段代码,就可以忽略HTTPS证书错误,让我们的程序能和HTTPS网站正确的交互了.
1 System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>2 {3 return true;4 };
1 public static string GetResponse(string url, string method, string data) 2 { 3 try 4 { 5 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 6 req.KeepAlive = true; 7 req.Method = method.ToUpper(); 8 req.AllowAutoRedirect = true; 9 req.CookieContainer = CookieContainers;10 req.ContentType = "application/x-www-form-urlencoded";11 12 req.UserAgent = IE7;13 req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";14 req.Timeout = 50000;15 16 if (method.ToUpper() == "POST" && data != null)17 {18 ASCIIEncoding encoding = new ASCIIEncoding();19 byte[] postBytes = encoding.GetBytes(data); ;20 req.ContentLength = postBytes.Length;21 Stream st = req.GetRequestStream();22 st.Write(postBytes, 0, postBytes.Length);23 st.Close();24 }25 26 System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>27 {28 return true;29 };30 31 Encoding myEncoding = Encoding.GetEncoding("UTF-8");32 33 HttpWebResponse res = (HttpWebResponse)req.GetResponse();34 Stream resst = res.GetResponseStream();35 StreamReader sr = new StreamReader(resst, myEncoding);36 string str = sr.ReadToEnd();37 38 return str;39 }40 catch (Exception)41 {42 return string.Empty;43 }44 }
参考文章地址:http://www.cnblogs.com/TankXiao/archive/2012/02/20/2350421.html