我的方法是对每个 Query 参数使用 UriBuilder 和 Dictionary。然后你可以UrlEncode每个参数的值,这样你就可以得到一个有效的Url。
这就是您的代码的样子:
var ub = new UriBuilder("https", "api.stackexchange.com");
ub.Path = "/2.2/search/advanced";
// query string parameters
var query = new Dictionary<string,string> ();
query.Add("site", "*");
query.Add("q", "[c#] OR [f#]");
query.Add("filter", "!.UE46gEJXV)W0GSb");
query.Add("page","1");
query.Add("pagesize","2");
// iterate over each dictionary item and UrlEncode the value
ub.Query = String.Join("&",
query.Select(kv => kv.Key + "=" + WebUtility.UrlEncode(kv.Value)));
var wc = new MyWebClient();
wc.DownloadString(ub.Uri.AbsoluteUri).Dump("result");
这将导致ub.Uri.AbsoluteUri中的此网址:
https://api.stackexchange.com/2.2/search/advanced?site=*&q=%5Bc%23%5D+OR+%5Bf%23%5D&filter=!.UE46gEJXV)W0GSb&page=1&pagesize=2
由于 StackAPI 返回压缩后的内容,请在子类 WebClient 上使用 AutomaticDecompression(如 here 所示 feroze):
class MyWebClient:WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
var wr = base.GetWebRequest(uri) as HttpWebRequest;
wr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return wr;
}
}
当与其他代码结合时,会为我生成输出:
{
"items" : [{
"tags" : ["c#", "asp.net-mvc", "iis", "web-config"],
"last_activity_date" : 1503056272,
"question_id" : 45712096,
"link" : "https://*.com/questions/45712096/can-not-read-web-config-file",
"title" : "Can not read web.config file"
}, {
"tags" : ["c#", "xaml", "uwp", "narrator"],
"last_activity_date" : 1503056264,
"question_id" : 45753140,
"link" : "https://*.com/questions/45753140/narrator-scan-mode-for-textblock-the-narrator-reads-the-text-properties-twice",
"title" : "Narrator. Scan mode. For TextBlock the narrator reads the Text properties twice"
}
]
}