NZJames NZJames - 4 years ago 262
HTTP Question

Translating HTTP POST body to c# request

I have intercepted the POST request I need to simulate as


How do I send this in C# using HTTPClient? I found the following sample but this passes a dictionary. What do I need to construct to simulate the above request as it isn't clear to me

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();

Answer Source

I think HttpWebRequest is easier in your case.

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&para2=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();

PS. This sample code is copied from a Chinese website.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download