Home  >  Article  >  Backend Development  >  About Send WebRequest method and data processing in C#

About Send WebRequest method and data processing in C#

巴扎黑
巴扎黑Original
2016-12-19 16:27:021474browse

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;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn