我正在使用 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我发送查询字符串的最后一种方法GetAsync不起作用,我怀疑为什么会这样。当我 …
通过 抓取图像GetStreamAsync,如何确定状态?
HttpClient OpenClient = new HttpClient();
Stream firstImageStream = OpenClient.GetStreamAsync("imageUrl.jpg").Result;
Run Code Online (Sandbox Code Playgroud)
有时这会产生错误(通常为 403 或 404),我只想跳过处理这些结果。
我能找到的所有内容都说要使用StatusCode属性 or IsSuccessStatusCode,但那些似乎只适用于HttpResponseMessage来自 GetAsync 的 ,它没有给我Stream处理图像所需的条件。