我有几个开源库,它们是我从头开始编写或贡献的,它们使用相同的格式生成对API入口点的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可能是多余的。
发布于 2017-02-08 23:28:10
以下是Flurl如何在这里提供帮助(免责声明:我是作者):
var queryByPoint = _apiEntryPoint
.AppendPathSegment("weather")
.SetQueryParams(new { lat = latitude, lon = longitude, appid = _apiKey });Flurl的主要目标是启用building URLs in fluent, structured way (如果需要的话,只需抓取core package ),并流畅地调用这些URL并反序列化响应(抓取所有内容的Flurl.Http )。在启用testability、extensibility和cross-platform support方面已经投入了大量精力,我相信所有这些都使其成为API包装器库的理想之选。
https://stackoverflow.com/questions/42072137
复制相似问题