Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using TanksOnline.ProjektPZ.Server.Domain.Entities;
- using TanksOnline.ProjektPZ.Server.Domain.Enums;
- namespace HttpClientSample
- {
- class Program
- {
- static HttpClient client = new HttpClient();
- static void ShowUser(User user)
- {
- Console.WriteLine($"Name: {user.Name}\tEmail: {user.Email}\tBil mówi nie - passw :> {user.Password}");
- }
- static async Task<Uri> CreateUserAsync(User user)
- {
- HttpResponseMessage response = await client.PostAsJsonAsync("api/users", user);
- response.EnsureSuccessStatusCode();
- // return URI of the created resource.
- return response.Headers.Location;
- }
- static async Task<User> GetUserAsync(string path)
- {
- User product = null;
- HttpResponseMessage response = await client.GetAsync(path);
- if (response.IsSuccessStatusCode)
- {
- product = await response.Content.ReadAsAsync<User>();
- }
- return product;
- }
- static async Task<Product> UpdateProductAsync(Product product)
- {
- HttpResponseMessage response = await client.PutAsJsonAsync($"api/products/{product.Id}", product);
- response.EnsureSuccessStatusCode();
- // Deserialize the updated product from the response body.
- product = await response.Content.ReadAsAsync<Product>();
- return product;
- }
- static async Task<HttpStatusCode> DeleteProductAsync(string id)
- {
- HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");
- return response.StatusCode;
- }
- static void Main()
- {
- RunAsync().Wait();
- }
- static async Task RunAsync()
- {
- client.BaseAddress = new Uri("http://localhost:21021/");
- client.DefaultRequestHeaders.Accept.Clear();
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- try
- {
- // Create a new user
- User user = new User
- {
- Email = "test",
- Name = "test_name",
- Password = "awesomepassword",
- Status = UserStatus.Offline,
- TankInfo = new TankInfo() { Name = "RudyKurwaNa102" },
- UserScore = new UserScore()
- };
- var url = await CreateUserAsync(user);
- Console.WriteLine($"Created at {url}");
- // Get the product
- var useeer = await GetUserAsync(url.PathAndQuery);
- ShowUser(useeer);
- //// Update the product
- //Console.WriteLine("Updating price...");
- //product.Price = 80;
- //await UpdateProductAsync(product);
- //// Get the updated product
- //product = await GetProductAsync(url.PathAndQuery);
- //ShowProduct(product);
- // Delete the product
- //var statusCode = await DeleteProductAsync(product.Id);
- //Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement