我拦截了我需要模拟的POST请求
_method = POST&安培;数据%5BListing%5D%5Blisting_category_id%5D = 2及数据%5BListing%5D%5Blisting_subcategory_id%5D = 211
如何使用HTTPClient在C#中发送?我发现了以下示例,但是它传递了字典。我需要构建什么来模拟上述请求,因为我不清楚
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6740");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "login")
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
答案 0 :(得分:1)
我认为HttpWebRequest
在您的案例中更容易。
string Url = "http://localhost:6740";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
//POST method here.
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
//Parameters here.
string param = "para1=data1¶2=data2";
//Maybe you need unicode or other encoding...
byte[] bs = Encoding.ASCII.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
StreamReader sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
PS。此示例代码是从中文网站复制的。