读取HttpWebRequest的HTTP POST请求

本文关键字:POST 请求 HTTP HttpWebRequest 读取 | 更新日期: 2024-09-23 22:36:11

我需要为我正在编写的一些测试创建HttpPOST请求,也许还有一些GET请求作为字符串。目前,我的测试使用StringBuilder和从fiddler中提取的硬编码POST请求来构建它们,有点像这样:

var builder = new StringBuilder();
builder.Append("POST https://some.web.pg HTTP/1.1'r'n");
builder.Append("Content-Type: application/x-www-form-urlencoded'r'n");
builder.Append("Referer: https://some.referer.com'r'n");
builder.Append("Accept-Language: en-us'r'n");
builder.Append("Accept-Encoding: gzip, deflate'r'n");
builder.Append("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'r'n");
builder.Append("Host: login.yahoo.com'r'n");
//    ... other header info
builder.Append("'r'n");
builder.Append("post body......'r'n");
var postData = builder.ToString();

这很快让我的测试变得一团糟,我更希望有一种更干净的方式来构建这些POST请求。我一直在研究HttpWebRequest类,希望它能为我创建这些。但是遗憾的是,GetRequestStream是一个只能写入的流。

有没有办法读取HttpWebRequest将生成的请求流(然后将其更改为字符串)?甚至任何关于如何生成这些POST请求的想法都可以。

读取HttpWebRequest的HTTP POST请求

这里有一个msdn示例来发出Get请求:

using System;

使用System.Net;使用System.IO;

命名空间MakeAGETRequest_charp{//////Class1的摘要说明。///类别Class1{static void Main(string[]args){字符串sURL;sURL="http://www.microsoft.com";

        WebRequest wrGETURL;
        wrGETURL = WebRequest.Create(sURL);
        WebProxy myProxy = new WebProxy("myproxy",80);
        myProxy.BypassProxyOnLocal = true;
        wrGETURL.Proxy = WebProxy.GetDefaultProxy();
        Stream objStream;
        objStream = wrGETURL.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);
        string sLine = "";
        int i = 0;
        while (sLine!=null)
        {
            i++;
            sLine = objReader.ReadLine();
            if (sLine!=null)
                Console.WriteLine("{0}:{1}",i,sLine);
        }
        Console.ReadLine();
    }
}

}这里是一个用于post的请求(来自带有post的HTTP请求)

    HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create("http:''domain.com'page.asp");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream newStream = httpWReq.GetRequestStream())
{
    newStream.Write(data,0,data.Length);
}

我建议您使用mocking,因为它是单元测试的最佳实践:在stack上看到这个答案单元测试c#中的HTTP请求

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(yoururllink);
    var c = HttpContext.Current;
    //Set values for the request back
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
    string strRequest = Encoding.ASCII.GetString(param);
    string strResponse_copy = strRequest;  //Save a copy of the initial info sent from your url link
    strRequest += "&cmd=_notify-validate";
    req.ContentLength = strRequest.Length;
    //for proxy
    //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
    //req.Proxy = proxy;
    //Send the request to PayPal and get the response
    StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
    streamOut.Write(strRequest);
    streamOut.Close();
    StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
    string strResponse = streamIn.ReadToEnd();
    streamIn.Close();