C#中關於Send WebRequest 方法和資料處理

來源:互聯網
上載者:User
很久不更新部落格了,這次大概說一下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;
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.