[Windows (Phone) 8] How to submit a form and retrieve results in your application ?

January 2nd, 2014 | Posted by Tom in .NET | Article | Windows 8 | Windows Phone | Read: 3,531

Recently, I started to work on a Windows Phone application with all the data available through a Website (thanks to HtmlAgilityPack for helping me to parse the webpages).

All the parsing was quite easy but when I wanted to implement the search feature, I wondered how I could do this without any API ? Then, I discovered that the website was using a search form to propose the feature to its users so that was the way !

Here is the HTML code corresponding to the search form on the website:

<form method="post" action="http://www.mysyperwebsite.com/results.html">
    <input type="text" name="keyword" size="25" value="Enter some text..." onfocus="if (this.value=='Enter some text...') {this.value=''}" class="champs">&nbsp;
    <input type="button" onclick="ValidateSearch(this.form)" value="Search" alt="Search">
</form>

As we can see, the form send its data to the URL http://www.mysuperwebsite.com/results.html using the POST method. And that’s all we need to know! Indeed, we’ll do the same thing in our application: we’ll send a POST request to the indicated URL.

For that, we’ll use the HttpClient API and its PostAsync method (you can use the portable version of the HttpClient if you want). The PostAsync method takes in parameters the URI where to post the data and the content to send/post:

image

 

As we mimic the behavior of the form which post content, we’ll use the FormUrlEncodedContent object. This one takes in parameters a list of KeyValuePair, corresponding to the parameters sent by the search form:

var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

Here is the complete code:

var searchUri = "http://www.mysuperwebsite.com/results.html";
var searchParameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("keyword", searchText) };

using (var httpclient = new HttpClient())
{
    using (var content = new FormUrlEncodedContent(searchParameters))
    {
        using (var responseMessages = await httpclient.PostAsync(new Uri(searchUri, UriKind.Absolute), content))
        {
            return await responseMessages.Content.ReadAsStringAsync();
        }
    }
}

And voilà! Now, if you execute this code, it will be the same as if user use the search form.

 

Happy coding (and new year) ! :)

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

3 Responses



Add Comment Register



Leave a Reply