简体   繁体   English

在C#中使用多个URL参数构建列表

[英]Building a List with multiple URL Params in C#

I am trying to build a generic function that will run a simple HTTP Get request using various possible URL Params. 我正在尝试构建一个通用函数,该函数将使用各种可能的URL参数运行一个简单的HTTP Get请求。 I want to be able to receive a flexible number of strings as a parameter and add them one by one as a URL parameter in the request. 我希望能够接收数量灵活的字符串作为参数,并将其作为请求中的URL参数一个接一个地添加。 Here's my code so far, I am trying to build a List but for some reason I just can't muster a workign solution.. 到目前为止,这是我的代码,我正在尝试构建列表,但由于某种原因,我无法召集有效的解决方案。

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

Thanks! 谢谢!

I think you need this: 我认为您需要这样做:

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

Not so complex version with comments: 没有注释的复杂版本:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM