1 Nisan 2017 Cumartesi

REST Servis Cagırma

REST GET/POST/PUT/DELETE yapmak için uyguladığım adımlar şu şekilde:
  • Visual Studio’da Visual C#/Windows Desktop/Console Application projesi oluşturdum. Adını RestClientSample koydum.
  • NuGet üzerinden Microsoft.AspNet.WebApi.Client paketini yükledim.
  • Rest servise gönderilecek ve servisten dönecek nesnelere karşılık gelen sınıfları oluşturdum.
  • Program.cs’yi aşağıdaki gibi değiştirdim.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace RestClientSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RunAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
 
            Console.ReadKey();
        }
 
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                // Servis adresi
                client.BaseAddress = new Uri("http://webadresi.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                // Servis Basic Http Authentication istiyorsa eklenir.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(new UTF8Encoding().GetBytes(string.Format("{0}:{1}", "TestUser", "Pass"))));
 
                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/IotDatas/1");
                if (response.IsSuccessStatusCode)
                {
                    IotData product = await response.Content.ReadAsAsync<IotData>();
                    Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Value, product.CreateDate);
                }
 
                // HTTP POST
                var iotData = new IotData { Name = "Test", Value = null, CreateDate = DateTime.Now };
                response = await client.PostAsJsonAsync("api/IotDatas", iotData);
                if (response.IsSuccessStatusCode)
                {
                    Uri gizmoUrl = response.Headers.Location;
 
                    // HTTP PUT
                    iotData.Value = null;
                    response = await client.PutAsJsonAsync(gizmoUrl, iotData);
 
                    // HTTP DELETE
                    response = await client.DeleteAsync(gizmoUrl);
                }
            }
        }
    }
}

Hiç yorum yok: