很久不更新部落格了,這次大概說一下C#中的Send WebRequest,眾所周知,.NET網路程式設計在測試中是非常常見的,具體來說,例如我們如果測試一個API,透過Send WebRequest的方式來進行API層面的功能測試,然後用Selenium完成前端的驗證,這個模式應該說是比較方便而通用的,具體以其中最常見的HTTP request為例,當我們需要傳輸資料時,需要
1)位址: Address作為Webrequest參數實例化,然後設定對應屬性,例如Method(Get還是Post等等)
2)資料:Data作為HttpRequest的資料流寫入:
XmlResponse = null;
ResponseCode = HttpStatusC. ServerResponse = String.Empty;
參數處理部分
//Format the data
string output = data.Aggregate(String.Empty, (current, keyValuePair) => current + ("&" + ValuePair.Key + HttpUtility.UrlEncode(keyValuePair.Value)));
var encoding = new UTF8Encoding();
//設定PostData變數將output處理,最後得到byte[] d Encoding.ASCII.GetBytes(output);
byte[] d = encoding.GetBytes(output.Substring(1, output.Length - 1); GET部分的資料處理
if (method.ToUpperInvariant() == "GET")
address=address+output
//Add post process
if ( request == null)
throw new Exception("WebRequest object is null.");
request.Method = "POST";
request.ContentType = "application/xwww-form-urlencode. = d.Length;
ServerResponse = String.Empty;
//資料讀取與處理部分
using (Stream dataStream = request.GetRequestStream())
. ;
dataStream.Close();
using (var response = (HttpWebResponse)request.GetResponse ode = response.StatusCode;
using (Stream myStream = response.GetResponseStream())
if ( myStream != null)
var readStream = new StreamReader(myStream, Encoding.UTF8);
};
} response.Close();
if ( ResponseCode == HttpStatusCode.OK)
{
LoadXml();
返回 false;