HTTP请求重构

HTTP request refactoring

我有几个开源库,它们是我从头编写或贡献的,它们使用相同的格式生成对 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 请求和 return 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 可能是过度的。

以下是 Flurl 可以提供的帮助(免责声明:我是作者):

var queryByPoint = _apiEntryPoint
    .AppendPathSegment("weather")
    .SetQueryParams(new { lat = latitude, lon = longitude, appid = _apiKey });

Flurl 的主要目标是启用 building URLs in fluent, structured way (grab just the core package if that's all you need), and fluently calling those URLs and deserializing the response in about as few keystrokes as humanly possible (grab Flurl.Http for all the bits). Much effort has been put into enabling testability, extensibility, and cross-platform support,我相信所有这些都使其成为 API 包装器库的理想选择。