我有幾個開放源代碼庫,我從頭開始編寫或貢獻於使用相同的格式來生成到API入口點的HTTP請求。目前它們寫成如下:HTTP請求重構
private string _apiExtension = $"&appid={_apiKey}";
private string _apiEntryPoint = "http://api.openweathermap.org/data/2.5/";
public static string GenerateWebRequest(string conn)
{
try
{
if (!string.IsNullOrEmpty(conn))
{
using (var webClient = new WebClient())
{
return webClient.DownloadString(conn);
}
}
}
catch (WebException e)
{
Console.WriteLine(e.StackTrace);
}
return string.Empty;
}
用於生成HTTP請求並返回JSON響應。
然後我建立了conn
像這樣:
string queryByPoint = _apiEntryPoint + $"weather?lat={latitude}&lon={longitude}" + _apiExtension;
這看起來是這樣的:
http://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={_apiKey}
與_apiKey
和_apiEntryPoint
那些在構造函數初始化庫是字符串。
有沒有更好的方法來做到這一點?從小規模來看,構建一個連接字符串並不是完全重要的,但我覺得代碼重複,並且使用4行代碼來構建單個URL可能是過度的。
重複的4行代碼是什麼? – Aaron