Untitled
csharp
23 days ago
3.4 kB
6
Indexable
Never
using System.Text.Json; using System.Text; namespace main { class Kingdom { public static string ?jsonMessage; public static string endPointGetURL = ""; public static string endPointPostURL = ""; static string Jsonify(string message) { string jsonMessage = null; if (!string.IsNullOrWhiteSpace(message)) { jsonMessage = JsonSerializer.Serialize(message); } return jsonMessage; } static async Task<string> getRequest() { try { using (var client = new HttpClient()) { var response = await client.GetAsync(endPointGetURL); if (response.IsSuccessStatusCode) { // Read the content as a string string jsonMessage = await response.Content.ReadAsStringAsync(); // Display the content Console.WriteLine(jsonMessage); return jsonMessage; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } static async Task postRequest() { try { using (var client = new HttpClient()) { try { // Create the request content var content = new StringContent(jsonMessage, Encoding.UTF8, "application/json"); // Send the POST request var response = await client.PostAsync(endPointPostURL, content); // Check if the response is successful (status code 200) if (response.IsSuccessStatusCode) { var responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseContent); } else { Console.WriteLine($"Error: {response.StatusCode}"); } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } } static async Task Main() { while (true) { string i = Convert.ToString(Console.ReadLine()); if (Console.ReadKey().Key == ConsoleKey.Enter) { if (i == "/getRequest") { await Task.Delay(1000); await getRequest(); } else { var text = Console.ReadLine(); jsonMessage = Jsonify(JsonSerializer.Serialize(text)); await postRequest(); } } } } } }