首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTTP请求重构

HTTP请求重构
EN

Stack Overflow用户
提问于 2017-02-07 00:04:32
回答 1查看 101关注 0票数 0

我有几个开源库,它们是我从头开始编写或贡献的,它们使用相同的格式生成对API入口点的HTTP请求。目前它们的编写方式如下:

代码语言:javascript
复制
    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

代码语言:javascript
复制
string queryByPoint = _apiEntryPoint + $"weather?lat={latitude}&lon={longitude}" + _apiExtension;

它看起来像这样:

代码语言:javascript
复制
http://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={_apiKey}

其中_apiKey_apiEntryPoint是在库的构造函数中初始化的字符串。

有没有更好的方法来做这件事?在小规模上,构建一个连接字符串并不是很繁琐,但我觉得代码重复,使用4行代码来构建一个URL可能是多余的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-08 23:28:10

以下是Flurl如何在这里提供帮助(免责声明:我是作者):

代码语言:javascript
复制
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 )。在启用testabilityextensibilitycross-platform support方面已经投入了大量精力,我相信所有这些都使其成为API包装器库的理想之选。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42072137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档