在C#中构建具有多个URL参数的列表

时间:2015-04-16 08:09:57

标签: c# list httpwebrequest

我正在尝试构建一个泛型函数,它将使用各种可能的URL参数运行简单的HTTP Get请求。 我希望能够接收灵活数量的字符串作为参数,并在请求中逐个添加它们作为URL参数。 到目前为止,这是我的代码,我正在尝试建立一个列表,但出于某种原因,我只是不能制定一个有效的解决方案..

        public static void GetRequest(List<string> lParams)
    {
        lParams.Add(header1);
        string myURL = "";
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(myURL));
        WebReq.Method = "GET";
        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        sContent = _Answer.ReadToEnd();
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你需要这个:

private static string CreateUrl(string baseUrl, Dictionary<string, string> args)
{
    var sb = new StringBuilder(baseUrl);
    var f = true;
    foreach (var arg in args)
    {
        sb.Append(f ? '?' : '&');
        sb.Append(WebUtility.UrlEncode(arg.Key) + '=' + WebUtility.UrlEncode(arg.Value));
        f = false;
    }
    return sb.ToString();
}

带评论的版本不是那么复杂:

private static string CreateUrl(string baseUrl, Dictionary<string, string> parameters)
{
    var stringBuilder = new StringBuilder(baseUrl);
    var firstTime = true;

    // Going through all the parameters
    foreach (var arg in parameters)
    {
        if (firstTime)
        {
            stringBuilder.Append('?'); // first parameter is appended with a ? - www.example.com/index.html?abc=3
            firstTime = false; // All other following parameters should be added with a &
        }
        else
        {
            stringBuilder.Append('&'); // all  other parameters are appended with a & - www.example.com/index.html?abc=3&abcd=4&abcde=8
        }

        var key = WebUtility.UrlEncode(arg.Key); // Converting characters which are not allowed in the url to escaped values
        var value = WebUtility.UrlEncode(arg.Value); // Same goes for the value

        stringBuilder.Append(key + '=' + value); // Writing the parameter in the format key=value
    }

    return stringBuilder.ToString(); // Returning the url with parameters
}