簡體   English   中英

帶有查詢字符串的 HttpClient GetAsync

[英]HttpClient GetAsync with query string

我正在使用谷歌的地理編碼 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。

我不建議將 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);
        }
    }
}

Ciao,問題與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();
    }
}

正如谷歌表所說:

在您擁有 API 密鑰后,您的應用程序可以 append 查詢參數 key=yourAPIKey 到所有請求 URL。 API 密鑰可以安全地嵌入 URL; 它不需要任何編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM