Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate browser HTTP POST request and capture result in C#

Tags:

c#

http-post

Lets say we have a web page with a search input form, which submits data to server via HTTP GET. So that's mean server receive search data through query strings. User can see the URL and can also initialize this request by himself (via URL + Query strings).

We all know that. Here is the question.

What if this web page submits data to the server via HTTP POST? How can user initialize this request by himself?

Well I know how to capture HTTP POST (that's why network sniffers are for), but how can I simulate this HTTP POST request by myself in a C# code?

like image 702
Peter Stegnar Avatar asked Jan 15 '10 12:01

Peter Stegnar


People also ask

Can a browser make a POST request?

You cannot make a POST request by using a web browser, as web browsers only directly support GET requests.

How do I request POST from browser console?

The simplicity of pressing F12 , write the command in the console tab (or press the up key if you used it before) then press Enter , see it pending and returning the response is what making it really useful for simple POST requests tests.

Can we do POST using GET method?

POST is also more secure than GET , because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea. One final note: POST can transmit a larger amount of information than GET .


1 Answers

You could take a look at the WebClient class. It allows you to post data to an arbitrary url:

using (var client = new WebClient())
{
    var dataToPost = Encoding.Default.GetBytes("param1=value1&param2=value2");
    var result = client.UploadData("http://example.com", "POST", dataToPost);
    // do something with the result
}

Will generate the following request:

POST / HTTP/1.1
Host: example.com
Content-Length: 27
Expect: 100-continue
Connection: Keep-Alive

param1=value1&param2=value2
like image 101
Darin Dimitrov Avatar answered Sep 29 '22 22:09

Darin Dimitrov