Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post using HttpClient?

I am able to get a webpage using HttpClinet class as follows :

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(@"http://59.185.101.2:10080/jsp/Login.jsp");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();

The page will render two textboes, namely Username & Password. It will also render many hidden variables.

I want to post this rendered Html to desired address, but with my own values of username & password. (preserving the rest of the hidden variables)

How do I do this ?


PS: THIS IS A CONSOLE APPLICATION POC

like image 367
Bilal Fazlani Avatar asked Apr 06 '26 20:04

Bilal Fazlani


1 Answers

You could use the PostAsync method:

using (var client = new HttpClient())
{
    var content = new FormUrlEncodedContent(new[]
    { 
        new KeyValuePair<string, string>("username", "john"),
        new KeyValuePair<string, string>("password", "secret"),
    });
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    var response = await client.PostAsync(
        "http://59.185.101.2:10080/jsp/Login.jsp", 
        content
    );
    response.EnsureSuccessStatusCode();
    var responseBody = await response.Content.ReadAsStringAsync();
}

You will have to provide all the necessary input parameters that your server side script requires in the FormUrlEncodedContent content instance.

As far as the hidden variables are concerned, you will have to parse the HTML you retrieved from the first call, using an HTML parser such as HTML Agility Pack and include them in the collection for the POST request.

like image 184
Darin Dimitrov Avatar answered Apr 09 '26 11:04

Darin Dimitrov