发送NameValueCollection到http请求C# [英] Sending NameValueCollection to http request C#

查看:222
本文介绍了发送NameValueCollection到http请求C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况. 我们正在使用某种方法进行登录,但是该方法处于更高的抽象级别,因此它仅具有用户名和密码之类的参数,并且使用此参数进行了一些Name值收集,然后传递给了一些请求生成器.注入了此请求构建器,以便我可以更改其实现.现在我们正在使用POST请求,但是将来我们可能会使用XML或JSON,因此只需切换注入接口的实现即可.

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.

问题是我无法对任何使该System.Net.HttpWebRequest脱离此名称值集合的库进行罚款. 我需要这样的原型方法:

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.

谢谢.

推荐答案

我不是100%地确定您想要什么,但是要创建一个将发布NameNameCollection中的某些数据的Web请求,您可以使用以下方法:

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;
}

但是,您发布的数据将取决于您接受的格式.此示例使用查询字符串格式,但是如果您切换到JSON或其他方式,则只需要更改处理NameValueCollection的方式即可.

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.

这篇关于发送NameValueCollection到http请求C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆