Home > Article > Backend Development > About Send WebRequest method and data processing in C#
I haven’t updated my blog for a long time. This time I will briefly talk about Send WebRequest in C#. As we all know, .NET network programming is very common in testing. Specifically, if we test an API, we use Send WebRequest. Functional testing at the API level, and then using Selenium to complete front-end verification. This mode should be said to be more convenient and versatile. Specifically, take the most common HTTP request as an example. When we need to transmit data, we need
1) Address: Address is instantiated as a Webrequest parameter, and then the corresponding attributes are set, such as Method (Get or Post, etc.)
2) Data: Data is written as the data stream of HttpRequest:
XmlResponse = null;
ResponseCode = HttpStatusCode.Unused;
ServerResponse = String.Empty;
Parameter processing part
//Format the data
string output = data.Aggregate(String.Empty, (current, keyValuePair) => current + ("&" + keyValuePair.Key + "= " + HttpUtility.UrlEncode(keyValuePair.Value)));
var encoding = new UTF8Encoding();
//Set the PostData variable to process the output, and finally get byte[] d as the final data and write it into the WebRequest
var Postdata = Encoding.ASCII.GetBytes(output);
byte[] d = encoding.GetBytes(output.Substring(1, output.Length - 1));
var address = TargetUrl;
//Data processing in the GET part
if (method.toupperinvariant () == "get")
address = address+output;
// post data processing
webrequest request = webrequest.create (address) as httpwebrequest ; DADD 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;
//Data reading and processing part
using (Stream dataStream = request.GetRequestStream())
{
DataStream.Write(d, 0, d.Length ; ponseStream())
(myStream != null)
ServerResponse = readStream.ReadToEnd();
); (ResponseCode == HttpStatusCode.OK)
return true;
}
return false;