Webseite auslesen, mal wieder

  • VB.NET

Es gibt 18 Antworten in diesem Thema. Der letzte Beitrag () ist von Fakiz.

    Webseite auslesen, mal wieder

    Ich möchte diese Webseite auslesen:
    e6bx.com/weather/EDDN/?hoursBe…ncludeTaf=0&showDecoded=1



    Mich interessiert die Uhrzeit und die Temperatur. Der Quelltext gibt nicht viel her und wenn ich die Seite mit Chrome untersuche bekomme ich auch keine Daten.
    RegEx scheint eine mögliche Lösung zu sein aber da fehlt mir noch jeder Ansatz.
    Das EDDN in der URL kann durch jeden anderen Flughafen Code ersetzt werden, die Struktur der Anzeige ist aber immer gleich.
    Man(n) kann auch ohne Hunde leben, aber es lohnt nicht (Heinz Rühmann)
    Kannst bei gängigen Browsern mal in den Entwicklertools die Verbindungen beim Network tab beobachten, dann wirst du sehen, das ein Endpoint angesprochen wird, um die Daten abzuholen.

    Quellcode

    1. POST https://e6bx.com/secure?api=adds
    2. {"params":{"time":1623437673622,"stations":{"stationString":"EDDN"},"metars":{"stationString":"EDDN","hoursBeforeNow":3,"mostRecentForEachStation":true},"tafs":{"stationString":"EDDN","hoursBeforeNow":12,"mostRecentForEachStation":true}}}

    Die Antwort kommt im json format.
    @cf5730 Ich hab schon häufiger mal per AgilityPack oder wie @ISliceUrPanties oben gepostet hat AngelSharp etc. Webseiten untersucht/benutzt. Da konnte ich, aber immer den Quellcode runterladen und alle Infos standen da schon drin (im Quellcode).

    Gibt es denn einen Weg, wie man z.B. in einer Winforms Anwendung per Btn Click die Temperartur von dem Web-Link 'herholen' kann ohne einen API Zugang zu haben?!

    Wie ich eine Json-Antwort von einer API verarbeiten kann, wo es einen öffentlichen Api-Key gibt etc. hab ich schon häufiger gemacht. Aber hier ?!

    Wie bekomme ich die 'Versteckte' Antwort in mein C#-ClassenModel? Ich hab das Debug-Tool noch nie wirklich benutzt bis auf die Console (mal wieder ein Error :) ). Dank Deines Hinweises bin ich bis hier gekommen und konnte mir die Json-Antwort der Api schön ansehen.



    Wie wäre den der nächste Schritt, dass was ich da sehe programmatisch auszulesen?

    Ich kenn nur (NewtonSoft Json NuGet):
    Spoiler anzeigen

    C#-Quellcode

    1. string myJsonResponse = await client.GetStringAsync(
    2. "https://metals-api.com/api/latest?access_key=SecretApiKey&base=EUR&symbols=XAU");
    3. MyDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);



    So hab ich dann die Antwort der Api schön sauber in meinem Progamm. Geht so etwas auch mit 'nur' einem WebLink?!
    Bilder
    • vb2f.jpg

      369,72 kB, 1.425×1.159, 88 mal angesehen
    codewars.com Rank: 4 kyu
    @nogood
    Ich habe da mal ein Beispiel als Konsolenanwendung zusammengeschustert (.NET 5). Evtl. hilft das dir und dem Threadersteller weiter.

    C#-Quellcode

    1. using ConsoleApp4;
    2. using System;
    3. using System.Net.Http;
    4. var metars = new StationParam { HoursBeforeNow = 3, MostRecentForEachStation = true, StationString = "EDDN" };
    5. var tafs = new StationParam { HoursBeforeNow = 12, MostRecentForEachStation = true, StationString = "EDDN" };
    6. var requestPayload = new RequestPayload { Metars = metars, Stations = new() { StationString = "EDDN" }, Tafs = tafs };
    7. var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://e6bx.com/secure?api=adds");
    8. var contentString = System.Text.Json.JsonSerializer.Serialize(new Param { Params = requestPayload });
    9. requestMessage.Content = new StringContent(contentString);
    10. requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(System.Net.Mime.MediaTypeNames.Application.Json);
    11. requestMessage.Content.Headers.ContentLength = contentString.Length;
    12. using var client = new HttpClient();
    13. var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
    14. if (response.IsSuccessStatusCode)
    15. {
    16. Console.WriteLine(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
    17. }


    Spoiler anzeigen

    C#-Quellcode

    1. ​using System;
    2. using System.Text.Json.Serialization;
    3. namespace ConsoleApp4
    4. {
    5. public class Param
    6. {
    7. [JsonPropertyName("params")]
    8. public RequestPayload Params { get; set; }
    9. }
    10. public class RequestPayload
    11. {
    12. [JsonPropertyName("time")]
    13. public long Time { get; private set; }
    14. [JsonPropertyName("tafs")]
    15. public StationParam Tafs { get; set; }
    16. [JsonPropertyName("matars")]
    17. public StationParam Metars { get; set; }
    18. [JsonPropertyName("station")]
    19. public Station Stations { get; set; }
    20. public RequestPayload()
    21. {
    22. Time = DateTimeOffset.Now.ToUnixTimeSeconds();
    23. }
    24. }
    25. public class StationParam
    26. {
    27. [JsonPropertyName("hoursBeforeNow")]
    28. public int HoursBeforeNow { get; set; }
    29. [JsonPropertyName("mostRecentForEachStation")]
    30. public bool MostRecentForEachStation { get; set; }
    31. [JsonPropertyName("stationString")]
    32. public string StationString { get; set; }
    33. }
    34. public class Station
    35. {
    36. [JsonPropertyName("stationString")]
    37. public string StationString { get; set; }
    38. }
    39. }



    Es muss dann nur noch die Antwort in ein Objekt überführt oder irgendwie anders verarbeitet werden.
    Danke erstmal für eure Antworten aber das übersteigt meine Fähigkeiten bei weitem. Da werde ich wohl nicht weiterkommen.
    Man(n) kann auch ohne Hunde leben, aber es lohnt nicht (Heinz Rühmann)
    @Skino Gib noch nicht auf ... ist für mich auch noch zu hoch :)ABER @ISliceUrPanties hat fast die Lösung komplett geposted! DANKE dafür :thumbup:

    Hier noch ein bisschen Kontext für uns minder Bemittelte.

    Also mit Taste F12 in Chrom... dann 1-5 und man hat schon mal eine Idee was die Api als Request erwartet. Dann json2csharp.com oder ähnliches nutzen, um automatisch C# Classen zu generieren.
    Siehe @ISliceUrPanties Code: public class Param{...} Und anscheinend kann man sich dann eine 'Anfrage' zusammenstellen requestMessage. Die WebSide sendet auf den Request dann die Antwort und diese kann man dann weiter verarbeiten. Im Grunde genommen müsstes Du @Skino nur die Flughafen Kürzel variabel abfragen und könntest dann Infos per C# abfragen.



    Für mich sieht es so aus, dass die Antwort im Moment nur aus dem 'tats' Teil besteht und der 'metars' Teil aus mir nicht bekannten Gründe nicht zurück gesendet wird (in dem stehen jedoch die Infos die Du möchtest -Temp.-). An der Stelle müsste ich weiter testen, ob ich das hin bekomme. Oder IScliceUrPanties hat noch Langeweile genug und tippt dazu noch eine Antwort.

    Lg nogood und nochmal :thumbsup: für die Hilfe Slice

    Bilder
    • VBSol.jpg

      469,16 kB, 1.556×1.180, 73 mal angesehen
    • vbsol2.jpg

      130,12 kB, 646×435, 77 mal angesehen
    codewars.com Rank: 4 kyu
    @cf5730
    Ich steh immer noch auf dem Schlauch. Ich hab im Grunde genommen nur Slices Code in ein neues Konsolen Project kopiert.
    Ich bekomm dann diese Antwort als Json:

    Spoiler anzeigen
    {"tafs":[{"raw_text":"TAF EDDN 121700Z 1218/1318 29011KT 9999 FEW035 BECMG 1221/1223 31005KT BECMG 1308/1310 32010KT BECMG 1317/1318 33005KT","station_id":"EDDN","issue_time":"2021-06-12T17:00:00Z","bulletin_time":"2021-06-12T17:00:00Z","valid_time_from":"2021-06-12T18:00:00Z","valid_time_to":"2021-06-13T18:00:00Z","latitude":49.5,"longitude":11.05,"elevation_m":312,"forecast":[{"fcst_time_from":"2021-06-12T18:00:00Z","fcst_time_to":"2021-06-12T21:00:00Z","wind_dir_degrees":290,"wind_speed_kt":11,"visibility_statute_mi":6.21,"sky_condition":[{"sky_cover":"FEW","cloud_base_ft_agl":3500}]},{"fcst_time_from":"2021-06-12T21:00:00Z","fcst_time_to":"2021-06-13T08:00:00Z","change_indicator":"BECMG","time_becoming":"2021-06-12T23:00:00Z","wind_dir_degrees":310,"wind_speed_kt":5,"visibility_statute_mi":6.21,"sky_condition":[{"sky_cover":"FEW","cloud_base_ft_agl":3500}]},{"fcst_time_from":"2021-06-13T08:00:00Z","fcst_time_to":"2021-06-13T17:00:00Z","change_indicator":"BECMG","time_becoming":"2021-06-13T10:00:00Z","wind_dir_degrees":320,"wind_speed_kt":10,"visibility_statute_mi":6.21,"sky_condition":[{"sky_cover":"FEW","cloud_base_ft_agl":3500}]},{"fcst_time_from":"2021-06-13T17:00:00Z","fcst_time_to":"2021-06-13T18:00:00Z","change_indicator":"BECMG","time_becoming":"2021-06-13T18:00:00Z","wind_dir_degrees":330,"wind_speed_kt":5,"visibility_statute_mi":6.21,"sky_condition":[{"sky_cover":"FEW","cloud_base_ft_agl":3500}]}]}]}


    Ich hab da nichts weggelassen. Es ist ein Obj. tafs mit 4x Weatherforcastes. Ich hab mir den Code daraufhin angesehen, aber nichts gefunden wo ich sagen würde daher kommt das.
    Lg nogood

    ---
    hier mein komplettes Listing (.net 5 Visual Studio Consolen Project) und das NewtonSoft.Json Nuget installiert (aber auch nur für das spätere deserializen):
    Spoiler anzeigen

    C#-Quellcode

    1. ​using System;
    2. using System.Text.Json.Serialization;
    3. using System.Net.Http;
    4. using System.Threading.Tasks;
    5. using Newtonsoft.Json;
    6. using System.Collections.Generic;
    7. namespace CS_FlugplatzWebScraping
    8. {
    9. //https://www.vb-paradise.de/index.php/Thread/133576-Webseite-auslesen-mal-wieder/?postID=1153886#post1153886
    10. //https://e6bx.com/weather/EDDN/?hoursBeforeNow=0&includeTaf=0&showDecoded=1
    11. //--------------------ISliceUrPanties
    12. class Program
    13. {
    14. static async Task Main(string[] args)
    15. {
    16. var metars = new StationParam { HoursBeforeNow = 3, MostRecentForEachStation = true, StationString = "EDDN" };
    17. var tafs = new StationParam { HoursBeforeNow = 12, MostRecentForEachStation = true, StationString = "EDDN" };
    18. var requestPayload = new RequestPayload { Metars = metars, Stations = new() { StationString = "EDDN" }, Tafs = tafs };
    19. var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://e6bx.com/secure?api=adds");
    20. var contentString = System.Text.Json.JsonSerializer.Serialize(new Param { Params = requestPayload });
    21. requestMessage.Content = new StringContent(contentString);
    22. requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(System.Net.Mime.MediaTypeNames.Application.Json);
    23. requestMessage.Content.Headers.ContentLength = contentString.Length;
    24. using var client = new HttpClient();
    25. var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
    26. if (response.IsSuccessStatusCode)
    27. {
    28. var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    29. Console.WriteLine(res);
    30. //-------------nogood
    31. //'put/get' response in the Class struct from below
    32. Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(res);
    33. Console.WriteLine($" \n \n EDDN Elevation: {myDeserializedClass.Tafs[0].ElevationM} m");
    34. //^^^^^^^^^^^^^nogood
    35. }
    36. }
    37. }
    38. public class Param
    39. {
    40. [JsonPropertyName("params")]
    41. public RequestPayload Params { get; set; }
    42. }
    43. public class RequestPayload
    44. {
    45. [JsonPropertyName("time")]
    46. public long Time { get; private set; }
    47. [JsonPropertyName("tafs")]
    48. public StationParam Tafs { get; set; }
    49. [JsonPropertyName("matars")]
    50. public StationParam Metars { get; set; }
    51. [JsonPropertyName("station")]
    52. public Station Stations { get; set; }
    53. public RequestPayload()
    54. {
    55. Time = DateTimeOffset.Now.ToUnixTimeSeconds();
    56. }
    57. }
    58. public class StationParam
    59. {
    60. [JsonPropertyName("hoursBeforeNow")]
    61. public int HoursBeforeNow { get; set; }
    62. [JsonPropertyName("mostRecentForEachStation")]
    63. public bool MostRecentForEachStation { get; set; }
    64. [JsonPropertyName("stationString")]
    65. public string StationString { get; set; }
    66. }
    67. public class Station
    68. {
    69. [JsonPropertyName("stationString")]
    70. public string StationString { get; set; }
    71. }
    72. //^^^^^^^^^^^^^^^^^^^ISliceUrPanties
    73. //-------------------nogood
    74. //Autocreated Code via : https://json2csharp.com // just copy the JsonResponde from ISliceUrPantiesConsolApp into the WebApp
    75. // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    76. public class SkyCondition
    77. {
    78. [JsonProperty("sky_cover")]
    79. public string SkyCover { get; set; }
    80. }
    81. public class Forecast
    82. {
    83. [JsonProperty("fcst_time_from")]
    84. public DateTime FcstTimeFrom { get; set; }
    85. [JsonProperty("fcst_time_to")]
    86. public DateTime FcstTimeTo { get; set; }
    87. [JsonProperty("wind_dir_degrees")]
    88. public int WindDirDegrees { get; set; }
    89. [JsonProperty("wind_speed_kt")]
    90. public int WindSpeedKt { get; set; }
    91. [JsonProperty("visibility_statute_mi")]
    92. public double VisibilityStatuteMi { get; set; }
    93. [JsonProperty("wx_string")]
    94. public string WxString { get; set; }
    95. [JsonProperty("sky_condition")]
    96. public List<SkyCondition> SkyCondition { get; set; }
    97. [JsonProperty("change_indicator")]
    98. public string ChangeIndicator { get; set; }
    99. [JsonProperty("wind_gust_kt")]
    100. public int? WindGustKt { get; set; }
    101. [JsonProperty("time_becoming")]
    102. public DateTime? TimeBecoming { get; set; }
    103. }
    104. public class Taf
    105. {
    106. [JsonProperty("raw_text")]
    107. public string RawText { get; set; }
    108. [JsonProperty("station_id")]
    109. public string StationId { get; set; }
    110. [JsonProperty("issue_time")]
    111. public DateTime IssueTime { get; set; }
    112. [JsonProperty("bulletin_time")]
    113. public DateTime BulletinTime { get; set; }
    114. [JsonProperty("valid_time_from")]
    115. public DateTime ValidTimeFrom { get; set; }
    116. [JsonProperty("valid_time_to")]
    117. public DateTime ValidTimeTo { get; set; }
    118. [JsonProperty("latitude")]
    119. public double Latitude { get; set; }
    120. [JsonProperty("longitude")]
    121. public double Longitude { get; set; }
    122. [JsonProperty("elevation_m")]
    123. public int ElevationM { get; set; }
    124. [JsonProperty("forecast")]
    125. public List<Forecast> Forecast { get; set; }
    126. }
    127. public class Root
    128. {
    129. [JsonProperty("tafs")]
    130. public List<Taf> Tafs { get; set; }
    131. }
    132. //^^^^^^^^^^^^^^^^^^^nogood
    133. }
    codewars.com Rank: 4 kyu
    Ich hab dir mal eine Beispiel -Projektmappe erstellt (als Dateianhang und im Spoiler). Diese beinhaltet sowohl ein C# und ein äquivalentes VbNet Projekt. Zu beachten ist das ich mich hier nur auf die Metars Daten beschränke da diese die Temperatur und die Uhrzeit beinhalten. Und es werden nur die benötigten JSON Eigenschaften expliziet Deserializiert also die Eigenschaften observation_time & temp_c. Für die De/Serializierung verwende ich System.Text.Json. Für die Kommunikation mit dem Server verwende ich die WebRequest Klasse.

    Links die du dir angucken könntest:
    How to serialize and deserialize (marshal and unmarshal) JSON in .NET
    How to: Send data by using the WebRequest class


    ProjektMappe

    C#

    Program.cs

    C#-Quellcode

    1. using System;
    2. using System.IO;
    3. using System.Net;
    4. using System.Text;
    5. using System.Text.Json;
    6. using VbParadiseWeatherForecast.JSONSerializable.Request;
    7. using VbParadiseWeatherForecast.JSONSerializable.Response;
    8. namespace VbParadiseWeatherForecast
    9. {
    10. class Program
    11. {
    12. static void Main(string[] args)
    13. {
    14. // JSON bytes die die POST Daten repräsentieren
    15. PostData postData = new PostData(DateTime.Now);
    16. string jsonString = JsonSerializer.Serialize(postData);
    17. byte[] postDataBytes = Encoding.UTF8.GetBytes(jsonString);
    18. // HTTPWebRequest erstellen
    19. HttpWebRequest request = WebRequest.Create("https://e6bx.com/secure?api=adds") as HttpWebRequest;
    20. request.Method = "POST";
    21. request.ContentType = "application/x-www-form-urlencoded";
    22. request.ContentLength = postDataBytes.Length;
    23. // POST -Daten schreiben
    24. using (Stream dataStream = request.GetRequestStream())
    25. dataStream.Write(postDataBytes, 0, postDataBytes.Length);
    26. // Server -Antwort abfragen
    27. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    28. // Server -Antwort lesen
    29. string responseString;
    30. using (Stream responseStream = response.GetResponseStream())
    31. using (StreamReader sr = new StreamReader(responseStream))
    32. responseString = sr.ReadToEnd();
    33. // Im falle eines Positiven Status codes Deserializieren wir die Server -Antwort
    34. if (response.StatusCode == HttpStatusCode.OK)
    35. {
    36. ResponseData responseData = JsonSerializer.Deserialize<ResponseData>(responseString);
    37. Console.WriteLine("ObservationTime: {0}\r\nCurrentTemp: {1}", responseData.Metars[0]?.ObservationTime, responseData.Metars[0]?.TempCurrent);
    38. }
    39. else
    40. {
    41. Console.WriteLine("StatusCode: {0}, Response: {1}", response.StatusCode, responseString);
    42. }
    43. Console.ReadLine();
    44. }
    45. }
    46. }



    Requst.Metars

    C#-Quellcode

    1. using System.Text.Json.Serialization;
    2. namespace VbParadiseWeatherForecast.JSONSerializable.Request
    3. {
    4. public class Metars
    5. {
    6. [JsonPropertyName("StationString")]
    7. public string StationString { get; set; } = "EDDN";
    8. [JsonPropertyName("hoursBeforeNow")]
    9. public int HoursBeforeNow { get; set; } = 3;
    10. [JsonPropertyName("mostRecentForEachStation")]
    11. public bool MostRecentForEachStation { get; set; } = true;
    12. }
    13. }



    Request.Params

    C#-Quellcode

    1. using System.Text.Json.Serialization;
    2. namespace VbParadiseWeatherForecast.JSONSerializable.Request
    3. {
    4. public class Params
    5. {
    6. [JsonPropertyName("time")]
    7. public int Time { get; set; }
    8. [JsonPropertyName("stations")]
    9. public Stations Stations { get; set; }
    10. [JsonPropertyName("metars")]
    11. public Metars Metars { get; set; }
    12. }
    13. }



    Request.PostData

    C#-Quellcode

    1. using System;
    2. using System.Text.Json.Serialization;
    3. namespace VbParadiseWeatherForecast.JSONSerializable.Request
    4. {
    5. public class PostData
    6. {
    7. [JsonPropertyName("params")]
    8. public Params Params { get; set; }
    9. public PostData() { }
    10. public PostData(DateTime time)
    11. {
    12. int iTime = (int)new TimeSpan(time.Day, time.Hour, time.Minute, time.Second).TotalMilliseconds;
    13. Params = new Params
    14. {
    15. Time = iTime,
    16. Stations = new Stations(),
    17. Metars = new Metars()
    18. };
    19. }
    20. }
    21. }



    Request.Stations

    C#-Quellcode

    1. using System.Text.Json.Serialization;
    2. namespace VbParadiseWeatherForecast.JSONSerializable.Request
    3. {
    4. public class Stations
    5. {
    6. [JsonPropertyName("stationString")]
    7. public string StationString { get; set; } = "EDDN";
    8. }
    9. }



    Response.MetarsItem

    C#-Quellcode

    1. using System.Collections.Generic;
    2. using System.Text.Json;
    3. using System.Text.Json.Serialization;
    4. namespace VbParadiseWeatherForecast.JSONSerializable.Response
    5. {
    6. public class MetarsItem
    7. {
    8. [JsonPropertyName("observation_time")]
    9. public string ObservationTime { get; set; }
    10. [JsonPropertyName("temp_c")]
    11. public int TempCurrent { get; set; }
    12. [JsonExtensionData]
    13. public Dictionary<string, JsonElement> ExtensionData { get; set; }
    14. }
    15. }



    Response.ResponseData

    C#-Quellcode

    1. using System.Collections.Generic;
    2. using System.Text.Json;
    3. using System.Text.Json.Serialization;
    4. namespace VbParadiseWeatherForecast.JSONSerializable.Response
    5. {
    6. public class ResponseData
    7. {
    8. [JsonPropertyName("metars")]
    9. public List<MetarsItem> Metars { get; set; }
    10. [JsonExtensionData]
    11. public Dictionary<string, JsonElement> ExtensionData { get; set; }
    12. }
    13. }




    VbNet


    Module1.vb

    VB.NET-Quellcode

    1. Imports System.IO
    2. Imports System.Net
    3. Imports System.Text
    4. Imports System.Text.Json
    5. Module Module1
    6. Sub Main()
    7. ' JSON bytes die die POST Daten repräsentieren
    8. Dim postData As PostData = New PostData(DateTime.Now)
    9. Dim jsonString As String = JsonSerializer.Serialize(postData)
    10. Dim postDataBytes As Byte() = Encoding.UTF8.GetBytes(jsonString)
    11. ' HTTPWebRequest erstellen
    12. Dim request As HttpWebRequest = TryCast(WebRequest.Create("https://e6bx.com/secure?api=adds"), HttpWebRequest)
    13. request.Method = "POST"
    14. request.ContentType = "application/x-www-form-urlencoded"
    15. request.ContentLength = postDataBytes.Length
    16. ' POST -Daten schreiben
    17. Using dataStream As Stream = request.GetRequestStream()
    18. dataStream.Write(postDataBytes, 0, postDataBytes.Length)
    19. End Using
    20. ' Server -Antwort abfragen
    21. Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
    22. Dim responseString As String
    23. ' Server -Antwort lesen
    24. Using responseStream As Stream = response.GetResponseStream()
    25. Using sr As StreamReader = New StreamReader(responseStream)
    26. responseString = sr.ReadToEnd()
    27. End Using
    28. End Using
    29. ' Im falle eines Positiven Status codes Deserializieren wir die Server -Antwort
    30. If response.StatusCode = HttpStatusCode.OK Then
    31. Dim responseData As ResponseData = JsonSerializer.Deserialize(Of ResponseData)(responseString)
    32. Console.WriteLine("ObservationTime: {0}{1}CurrentTemp: {2}", responseData.Metars(0)?.ObservationTime, vbCrLf, responseData.Metars(0)?.TempCurrent)
    33. Else
    34. Console.WriteLine("StatusCode: {0}, Response: {1}", response.StatusCode, responseString)
    35. End If
    36. Console.ReadLine()
    37. End Sub
    38. End Module



    Request.Metars

    VB.NET-Quellcode

    1. Imports System.Text.Json.Serialization
    2. Public Class Metars
    3. <JsonPropertyName("StationString")>
    4. Public Property StationString As String = "EDDN"
    5. <JsonPropertyName("hoursBeforeNow")>
    6. Public Property HoursBeforeNow As Integer = 3
    7. <JsonPropertyName("mostRecentForEachStation")>
    8. Public Property MostRecentForEachStation As Boolean = True
    9. End Class



    Request.Params

    VB.NET-Quellcode

    1. Imports System.Text.Json.Serialization
    2. Public Class Params
    3. <JsonPropertyName("time")>
    4. Public Property Time As Integer
    5. <JsonPropertyName("stations")>
    6. Public Property Stations As Stations
    7. <JsonPropertyName("metars")>
    8. Public Property Metars As Metars
    9. End Class



    Request.PostData

    VB.NET-Quellcode

    1. Imports System.Text.Json.Serialization
    2. Public Class PostData
    3. <JsonPropertyName("params")>
    4. Public Property Params As Params
    5. Public Sub New()
    6. End Sub
    7. Public Sub New(ByVal time As DateTime)
    8. Dim iTime As Integer = CInt(New TimeSpan(time.Day, time.Hour, time.Minute, time.Second).TotalMilliseconds)
    9. Params = New Params With {
    10. .Time = iTime,
    11. .Stations = New Stations(),
    12. .Metars = New Metars()
    13. }
    14. End Sub
    15. End Class



    Request.Stations

    VB.NET-Quellcode

    1. Imports System.Text.Json.Serialization
    2. Public Class Stations
    3. <JsonPropertyName("stationString")>
    4. Public Property StationString As String = "EDDN"
    5. End Class




    Response.MetarsItem

    VB.NET-Quellcode

    1. Imports System.Text.Json
    2. Imports System.Text.Json.Serialization
    3. Public Class MetarsItem
    4. <JsonPropertyName("observation_time")>
    5. Public Property ObservationTime As String
    6. <JsonPropertyName("temp_c")>
    7. Public Property TempCurrent As Integer
    8. <JsonExtensionData>
    9. Public Property ExtensionData As Dictionary(Of String, JsonElement)
    10. End Class



    Response.ResponseData

    VB.NET-Quellcode

    1. Imports System.Text.Json
    2. Imports System.Text.Json.Serialization
    3. Public Class ResponseData
    4. <JsonPropertyName("metars")>
    5. Public Property Metars As List(Of MetarsItem)
    6. <JsonExtensionData>
    7. Public Property ExtensionData As Dictionary(Of String, JsonElement)
    8. End Class




    Dateien
    • Example.rar

      (33,25 kB, 63 mal heruntergeladen, zuletzt: )
    Da nur eine Synchrone Abfrage gestellt wird und der Konstruktor auch nicht verwendet wird sehe ich hier kein Problem. Wenn die Abfrage asynchron wäre oder mehrere Anfragen in Folge ausgeführt würden wäre HttpClient sicherlich die bessere Wahl.

    Fakiz schrieb:

    wäre HttpClient sicherlich die bessere Wahl

    HttpClient ist IMMER die bessere Wahl. Neben dem, dass die Doku schon sagt, verwende HttpWebRequest nicht, hier weitere Gründe: Man kann die selbe Instanz eines HttpWebRequests nicht für weitere Anfragen verwenden. Das führt dann dazu, wenn eine neue Instanz erzeugt und eine Anfrage gemacht wird, dass die Anfrage über einen neuen Port gemacht wird. Das ist nicht nur schlecht für die Performance eines Programms, sondern führt (sicherlich nicht in diesem Fall) dann irgendwann zu aufgebrauchten Ports.
    Dann wäre da noch die Verwendung im Code. Ich meine, du hantierst mit Streams im Code, ständig muss irgendwas gecastet werden. Ist halt nicht so "straight forward" das Ganze.

    Skino schrieb:

    bekomme aber eine Fehlermeldung:

    docs.microsoft.com/de-de/dotne…-how-to?pivots=dotnet-5-0 du musst mindestens .NET Framework 4.7.2 oder höher installiert haben, damit du System.Text.Json verwenden kannst.