iT邦幫忙

0

抓去政府天氣api時,回傳第一次成功200,第二次發生401(USE .net core)

  • 分享至 

  • xImage

我直接用網址去打都ok,但只要用後端去呼叫第二次開始就會變40
測試swagger的時候,發現只有故意打錯api授權token才會變401,實在不清楚為何第二次會變成401...

 static async Task<string> GetWeather()
        {
            try
            {
                string result = "";
                string local = "新竹市";
                string Path = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization={API_TOKEN}&locationName="+ local;
            
                using HttpResponseMessage response = await client.GetAsync(Path);
                //Console.WriteLine(response.ToString());

                if (response.IsSuccessStatusCode == true)
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    WeatherReturn responseBodyJsonParse = JsonConvert.DeserializeObject<WeatherReturn>(responseBody);
                    var StartTime = Convert.ToDateTime(responseBodyJsonParse.records.location[0].weatherElement[0].time[1].startTime).ToString("yyyy  MM / dd dddd HH:mm");
                    var EndTime = Convert.ToDateTime(responseBodyJsonParse.records.location[0].weatherElement[0].time[1].endTime).ToString("yyyy  MM / dd dddd HH:mm");
                    result = "新竹市12小時天氣預報" +
                                                           Environment.NewLine + $"{StartTime}" +
                                                           Environment.NewLine + $"{EndTime}" +
                                                           Environment.NewLine + $"天氣狀態:{responseBodyJsonParse.records.location[0].weatherElement[0].time[0].parameter.parameterName}" +
                                                           Environment.NewLine + $"降雨機率:{responseBodyJsonParse.records.location[0].weatherElement[1].time[0].parameter.parameterName}" + "%" +
                                                           Environment.NewLine + $"最低溫度:{responseBodyJsonParse.records.location[0].weatherElement[2].time[0].parameter.parameterName}" + "°C" +
                                                           Environment.NewLine + $"最高溫度:{responseBodyJsonParse.records.location[0].weatherElement[4].time[0].parameter.parameterName}" + "°C" +
                                                           Environment.NewLine + $"天氣舒適度:{responseBodyJsonParse.records.location[0].weatherElement[3].time[0].parameter.parameterName}";
                    Console.WriteLine("抓取天氣API成功!");

                }
                else if (response.IsSuccessStatusCode == false)
                {
                    Console.WriteLine("抓取天氣API失敗!");
                    return result;
                }
                return result;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("抓取天氣失敗!");
                Console.WriteLine("Message :{0} ", e.Message.ToString());
                return "";
            }

        }

200時
https://ithelp.ithome.com.tw/upload/images/20221220/20136789VbhM9SUxqZ.jpg
401時
https://ithelp.ithome.com.tw/upload/images/20221220/20136789YI5WYmFGbo.jpg

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
johncoc
iT邦新手 3 級 ‧ 2022-12-20 15:54:29

200 跟 401 的 ContentType 不一樣
程式裡把 ContentType 統一設定成 application/json
可以參考這篇

1
jack8900
iT邦新手 1 級 ‧ 2022-12-20 17:01:14

比較懶人的做法
Program.cs

builder.Services.AddHttpClient("WeatherApi", (option) =>
{
    option.BaseAddress = new Uri("https://opendata.cwb.gov.tw/api/v1/rest/datastore/");
    option.DefaultRequestHeaders.Add("Accept", "application/json");
    option.DefaultRequestHeaders.Add("Authorization", "寫自己的授權碼");
});

Controller.cs

private readonly IHttpClientFactory _httpClientFactory;

public WeatherControllerController(IHttpClientFactory httpClientFactory)
{
    _httpClientFactory = httpClientFactory;
}

public async Task<IActionResult> GetWeather(string city)
{
    HttpClient httpClient = _httpClientFactory.CreateClient("WeatherApi");
    var response = await httpClient.GetAsync($"F-C0032-001?format=JSON" +
        $"&locationName={city}");
    //await response.Content.ReadAsStringAsync()
    //上面讀出資料之後
    //後面看你自己要怎樣處理
}
1
科科
iT邦好手 8 級 ‧ 2022-12-21 09:49:26

我剛好之前有接來用,寫法跟你差不多,但我都有成功,
你有確認你的授權碼是有效的嗎? 401表示回你未授權。

以下簡單一段給你參考

      string url = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001";
      string parameter = $"?Authorization={_settings.Authorization}&format=JSON&locationName=臺北市";

      StringBuilder SB = new StringBuilder();

      HttpClient _httpClient = _clientFactory.CreateClient();
      _httpClient.BaseAddress = new Uri(url);

      var response = await _httpClient.GetAsync(url + parameter).ConfigureAwait(false);
        var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(

我要發表回答

立即登入回答