2015-04-16 94 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

簡化方法併爲你評論 –

相關問題