Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending NameValueCollection to http request C#

I have this situation. We're using some method for login, but that method is on some higher abstraction level so it only have parameters like username and password and and that make some Name value collection with this params and than that passes to some request builder. This request builder is injected so that I can change it's implementation. Now we're using POST request, but in future we might use XML or JSON so will just switch the implementation of injected interface.

The problem is that I cannot fine any library which will make me System.Net.HttpWebRequest out of this name value collection. I need method with prototype like this:

WebRequest / HttpWebRequest  CreateRequest(Uri / string, nameValueCollection);

Or if there is no something like that, the library that does all the work (sending requests, receiving responses and parsing them) will be good too. But it needs to be async.

Thanks in advance.

like image 989
Vajda Avatar asked Aug 11 '11 08:08

Vajda


1 Answers

I'm not 100% sure what you want, but to create a web request that will post some data from a NameValueCollection, you can use something like this:

HttpWebRequest GetRequest(String url, NameValueCollection nameValueCollection)
{
    // Here we convert the nameValueCollection to POST data.
    // This will only work if nameValueCollection contains some items.
    var parameters = new StringBuilder();

    foreach (string key in nameValueCollection.Keys)
    {
        parameters.AppendFormat("{0}={1}&", 
            HttpUtility.UrlEncode(key), 
            HttpUtility.UrlEncode(nameValueCollection[key]));
    }

    parameters.Length -= 1;

    // Here we create the request and write the POST data to it.
    var request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.Method = "POST";

    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(parameters.ToString());
    }

    return request;
}

However, the data you post will depend upon the format you accept. This example uses query string format, but if you switch to JSON or something else you just need to change the way you process the NameValueCollection.

like image 143
Alex Humphrey Avatar answered Oct 22 '22 02:10

Alex Humphrey