2017-02-06 78 views
0

我有幾個開放源代碼庫,我從頭開始編寫或貢獻於使用相同的格式來生成到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可能是過度的。

+0

重複的4行代碼是什麼? – Aaron

回答

1

這裏是如何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,extensibilitycross-platform support,我相信所有這些使它非常適合API包裝程序庫。

+0

嘿,謝謝你的回覆。看起來正是我一直在尋找的,謝謝! –