带有查询字符串的 HttpClient GetAsync

HttpClient GetAsync with query string

我正在使用 Google 的地理编码 API。我有两种方法,一种有效,另一种无效,我似乎无法弄清楚原因:

string address = "1400,Copenhagen,DK";
string GoogleMapsAPIurl = "https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}";
string GoogleMapsAPIkey = "MYSECRETAPIKEY";
string requestUri = string.Format(GoogleMapsAPIurl, address.Trim(), GoogleMapsAPIkey);

// Works fine                
using (var client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(requestUri))
    {
        var responseContent = response.Content.ReadAsStringAsync().Result;
        response.EnsureSuccessStatusCode();
    }
}

// Doesn't work
using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/", UriKind.Absolute);
    client.DefaultRequestHeaders.Add("key", GoogleMapsAPIkey);

    using (HttpResponseMessage response = await client.GetAsync("geocode/json?address=1400,Copenhagen,DK"))
    {
        var responseContent = response.Content.ReadAsStringAsync().Result;
        response.EnsureSuccessStatusCode();
    }
}

我使用 GetAsync 发送查询字符串的最后一个方法不起作用,我怀疑为什么会这样。当我在客户端上引入 BaseAddress 时,GetAsync 不知何故不会发送到正确的 URL.

再见,问题与 URL 上的 key 参数有关。像这样更改您的代码:

using (HttpClient client = new HttpClient())
{
   client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/");
   
   using (HttpResponseMessage response = await client.GetAsync("geocode/json?address=1400,Copenhagen,DK&key=" + GoogleMapsAPIkey))
    {
       var responseContent = response.Content.ReadAsStringAsync().Result;
       response.EnsureSuccessStatusCode();
    }
}

正如google sheets所说:

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs. The API key is safe for embedding in URLs; it doesn't need any encoding.

我不建议将 API 键添加到全局变量中。也许您需要在 API 之外发送一些 HTTP 请求,这样密钥就会泄露。

这是有效的示例。

using Newtonsoft.Json;
public class Program
{
    private static readonly HttpClient client = new HttpClient();
    private const string GoogleMapsAPIkey = "MYSECRETAPIKEY";

    static async Task Main(string[] args)
    {
        client.BaseAddress = new Uri("https://maps.googleapis.com/maps/api/");

        try
        {
            Dictionary<string, string> query = new Dictionary<string, string>();
            query.Add("address", "1400,Copenhagen,DK");
            dynamic response = await GetAPIResponseAsync<dynamic>("geocode/json", query);
            Console.WriteLine(response.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadKey();
    }

    private static async Task<string> ParamsToStringAsync(Dictionary<string, string> urlParams)
    {
        using (HttpContent content = new FormUrlEncodedContent(urlParams))
            return await content.ReadAsStringAsync();
    }

    private static async Task<T> GetAPIResponseAsync<T>(string path, Dictionary<string, string> urlParams)
    {
        urlParams.Add("key", GoogleMapsAPIkey);
        string query = await ParamsToStringAsync(urlParams);
        using (HttpResponseMessage response = await client.GetAsync(path + "?" + query, HttpCompletionOption.ResponseHeadersRead))
        {
            response.EnsureSuccessStatusCode();
            string responseText = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(responseText);
        }
    }
}