Ana içeriğe atla

JSON ile Değer Döndüren Web Servis e HTTP Post Talebi

Bu sıralar çokca karşılaştığım bir süreci bloğumda da paylaşmak istedim.

.Net dışındaki dillerde web servis hazırlandığında genelde dönüş değeri olarak bu aralar popüler olan JSON ile değer döndürülüyor.Siz de bu web servise HTTP Post yöntemi ile C# üzerinden erişip işlem yapıyorsunuz.


Aşağıda ki metodu bir servise talep gönderip JSON olarak gelen dönüşü Generic Type dönüşümü ile istediğiniz tür de class veri tipine çevirme işlemi yaparak object oriented olarak projeniz de çalışabilirsiniz.

Not : Bu metodu kullanabilmeniz için http://www.newtonsoft.com/json adresindeki Newton json dll ini indirmeniz ve .Net projenize referans olarak eklemeniz gerekmektedir.Bu nesne json tipini bir class türüne, class türünden bir datanızı json türüne çevirimde kullanmanızda size yardımcı olacaktır.



       /// <summary>
        /// It provide that sent http post request and convert json response to entity tpye of T
        /// </summary>
        /// <typeparam name="T">Response Type For JSON Response</typeparam>
        /// <param name="postURL">HTTP Post URL</param>
        /// <param name="postData">HTTP Post Request Data type of string with seperate & character for ex : "username=test_user&password=1451"</param>
        /// <returns>return http post response with type of T</returns>
    private T SendHttpPost<T>(string postURL, string postData)
        {

            // Create a request using a URL that can receive a post.
            WebRequest request = WebRequest.Create(postURL);

            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array.
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();


            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string autResponseJsonString = reader.ReadToEnd();


            /*set variable to return type to getting http response which converted with NewtonJson Object DeserializeObject method*/
            T reponseData = JsonConvert.DeserializeObject<T>(autResponseJsonString);


            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

            return reponseData;

        }//End Method



Bu blogdaki popüler yayınlar

Cannot resolve the collation conflict between "Turkish_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the equal to operation.

iki ayrı veri tabanı içindeki tablolar ile işlem yapılmak istendiğinde eğer dil sorunu çıkıyor ise sorgumuzun sonuna 'COLLATE TURKISH_CI_AS' sözcüğünü ekleyerek sorunu çözebiliriz.Örnek : SELECT * FROM veritabani1.dbo.URUN u1 INNER JOIN veritabani2.dbo.URUNLER u2 ON u1.kod = u2.kod COLLATE TURKISH_CI_AS umarım faydalı olmuştur.

IEnumerable ile List Arasındaki Farklar

Sık kullandığımız iki tip olan IEnumerable ve List tipleri ile ilgili sürekli kullanılmasına rağmen farkının çok bilinmediğini düşünerek bu konuda kısa bir yazı yazmak istedim. Bakalım aralarında farklar nelermiş. IEnumerable bir interface iken, List yine IEnumerable sınıftan türeyen somut ( concrete) bir sınıftır. Arasındaki Farklar :  IEnumerable  - List e göre iteration çok daha hızlıdır. Performans için kullanılabilir.  - Read Only bir tip olduğu için Add, Remove gibi işlemler yapılamaz, IEnumerable ile sadece iteration, sort, filter gibi işlemler yapılabilir.  - Soyut bir class olduğu için istenen tipe somutlaştırılabilir.  - yield tipi ile birlikte kullanılabilir.(Promise veri döndürme,state-machine liste kullanımı)  - Linq sorguları veri tabanı sorgularınızın cevaplarınızı IEnumerable olarak döndürür, bu size siz ilgili IEnumerable list i iterate edene kadar ilgili sorguyu çalıştırmama performansı verir, böylece ilgili listeyi kullanmaya ihtiyacınız olmadığı bir durumda yada k

Logo (LOJECTS.exe ve LOBJECTS.dll) Register İşlemleri

LOBJECTS.dll register işlemi : başlat-> çalıştır -> cmd yazıp konsole ekranına geçiyoruz REGİSTER İÇİN : regsvr32 logoDosyaYolu\LOBJECTS.dll yazıyoruz ve dll imizi register ediyoruz UNREGISTER İÇİN : regsvr32 -u logoDosyaYolu\LOBJECTS.dll ile de unregister edebiliriz. LOBJECTS.exe register işlemi : başlat-> çalıştır -> cmd yazıp konsole ekranına geçiyoruz REGİSTER İÇİN : logoDosyaYolu\LOBJECTS.exe -REGSERVER yazıyoruz ve LOBJECTS.exe mizi register ediyoruz. UNREGISTER İÇİN : logoDosyaYolu\LOBJECTS.exe -UNREGSERVER yazıyoruz ve LOBJECTS.exe mizi unregister ediyoruz. Umarım yararlı olmuştur.