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

Netsis : "SQL : Select Sube_Kodu,MeRKEZMI,ISLETME_KODU FROM TBLSUBELER WITH (NOLOCK) Where Sube_Kodu = 0 " Login failed for user 'sa'.(NetsisM Hatası

Bu hatayı alıyorsanız muhtemelen Nesis in netopenx bileşenini kullanırken kernel nesnesi ile yeni şirket oluşturyorsunuzdur ve veri tabanı kullanıcı adı ve şifre kısmında hatalı parametre göndermişsinizdir. Netsis netopenx 3.0 sürümünden sonra kernel nesnesi ile yeni şirket oluşturuken bu kısıma VeriTabanı kullanıcı adına standart olarak "TEMELSET" yazmak gerekiyor ve şifre kısmınıda boş bırakmak gerekiyor.Netsis kendi içinden bu şifreyi alıp dolduruyor. Umarım Faydalı olmuştur. :)