Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
The person who downvoted, care to comment anything? – bilal fazlani Jul 16 at 9:03
It's unclear why your question got downvoted. It looks like a valid question to me. – Darin Dimitrov Jul 16 at 9:12

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
Thanks Darin. I will give that a try. – bilal fazlani Jul 16 at 9:17
Is there any better way to do this btw ? – bilal fazlani Jul 16 at 9:19
would restsharp be better than html agility pack for this purpose ? – bilal fazlani Jul 16 at 10:32
1  
RestSharp and HTML Agility Pack are 2 entirely different libraries doing 2 entirely different things. So you cannot ask whether you can use one instead of the other. RestSharp is just an HTTP client that you could use instead of the HttpClient class which is built in .NET. HTML Agility Pack on the other hand is an HTML parser which allows you to parse and query an HTML document (that you have previously downloaded with an HTTP client such as RestSharp or HttpClient). – Darin Dimitrov Jul 16 at 10:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.