2015-04-16 95 views
0

我正在尝试构建一个通用函数,该函数将使用各种可能的URL参数运行一个简单的HTTP Get请求。 我希望能够接收灵活数量的字符串作为参数,并将它们逐个添加为请求中的URL参数。 这里是到目前为止我的代码,我想建立一个列表,但由于某种原因,我不能鼓起workign解决方案..在C中构建一个包含多个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(); 
    } 

谢谢!

+0

哪些错误与'的GetRequest(字符串URL,则params字符串ARGS [])'? –

回答

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 
} 
+0

更改'if(f)f = false;'只是'f = false;'。没有必要检查它。 –

+0

这看起来很复杂..有没有办法简化它? –

+0

简化方法并为你评论 –

相关问题