"Enter"a basıp içeriğe geçin

C# WebRequest ile nesne post etme

C# ile istediğim nesneyi direk post edebileceğim hazır bir kütüphane bulamadığım için buraya yazıyorum. Şuan eksikleri var.Güncellenecektir.

 protected List<TEntity> HttpRequestGetList<TEntity>(object data, string url, string method = "POST")
        {
            try
            {
                string parameters = GenerateParameters(data);

                if (method == "GET" && data != null)
                {
                    url += "?" + parameters;
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = method;

                if (method == "POST" && data != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.CookieContainer = cookies;
                    httpWebRequest.ContentLength = parameters.Length;

                    StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                    requestWriter.Write(parameters);
                    requestWriter.Close();
                }

                HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;
                if (response == null) return new List<TEntity>();

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return new List<TEntity>();

                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string readToEnd = reader.ReadToEnd();

                    return JsonConvert.DeserializeObject<List<TEntity>>(readToEnd);
                }
            }
            catch
            {
                return new List<TEntity>();
            }
        }

        protected TEntity HttpRequestGetEntity<TEntity>(object data, string url, string method = "POST") where TEntity : new()
        {
            try
            {
                string parameters = GenerateParameters(data);

                if (method == "GET" && data != null)
                {
                    url += "?" + parameters;
                }

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Method = method;

                if (method == "POST" && data != null)
                {
                    CookieContainer cookies = new CookieContainer();
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.CookieContainer = cookies;
                    httpWebRequest.ContentLength = parameters.Length;

                    StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                    requestWriter.Write(parameters);
                    requestWriter.Close();
                }

                HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse;
                if (response == null) return new TEntity();

                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return new TEntity();

                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string readToEnd = reader.ReadToEnd();

                    return JsonConvert.DeserializeObject<TEntity>(readToEnd);
                }
            }
            catch
            {
                return new TEntity();
            }
        }

        private string GenerateParameters(object obj, string prefix = "")
        {
            if (obj == null)
                return "";

            string parameters = "";
            var propertyInfos = obj.GetType().GetProperties();
            foreach (PropertyInfo pInfo in propertyInfos)
            {
                var val = pInfo.GetValue(obj, null);
                if (val != null)
                {
                    if (pInfo.PropertyType.IsArray)
                    {
                        if (val.GetType().IsArray)
                        {
                            Array list = val as Array;
                            if (list != null)
                            {
                                for (int i = 0; i < list.Length; i++)
                                {
                                    parameters += prefix + pInfo.Name + "[" + i + "]=" + list.GetValue(i) + "&";
                                }
                            }
                        }
                    }
                    else if (pInfo.PropertyType.IsClass && pInfo.PropertyType.Name != "String")
                    {
                        parameters += GenerateParameters(val, pInfo.Name + ".") + "&";
                    }
                    else if (!string.IsNullOrWhiteSpace(val.ToString()))
                        parameters += prefix + pInfo.Name + "=" + val + "&";
                }
            }

            return string.IsNullOrWhiteSpace(parameters) ? "" : parameters.Substring(0, parameters.Length - 1);
        }

 

İlk Yorumu Siz Yapın

Bir Cevap Yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir