Sending nameValueCollection to C # http request

I have such a situation. We use some method to log in, but this method is at some higher level of abstraction, so it only has parameters such as username and password, and they make some collections of values ​​by name with these parameters, and then passed to some query builder. This query constructor is introduced so that I can change its implementation. Now we use the POST request, but in the future we can use XML or JSON, so just switch the implementation of the injected interface.

The problem is that I cannot distinguish any library that will make me System.Net.HttpWebRequest from this collection of name values. I need a prototype method:

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

Or, if there isn’t anything like that, a library that does all the work (sending requests, receiving answers and analyzing them) will also be good. But it must be asynchronous.

Thanks in advance.

+4
source share
2 answers

I'm not 100% sure what you want, but to create a web request that will output some data from 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 publish will depend on the format you accept. This example uses the format of the query string, but if you switch to JSON or something else, you just need to change the way NameValueCollection .

+9
source

From webclient load values

 NameValueCollection data; string str2 = string.Empty; StringBuilder builder = new StringBuilder(); foreach (string str3 in data.AllKeys) { builder.Append(str2); builder.Append(UrlEncode(str3)); builder.Append("="); builder.Append(UrlEncode(data[str3])); str2 = "&"; } 
0
source

All Articles