🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / C# RMOS / HttpClient basit kullanımı utf8 destekli httpwebclient

1-) C# RMOS - HttpClient basit kullanımı utf8 destekli httpwebclient

 

mesaj.Replace("\r\n","\\n"); // gönderilen jsonda alt satıra geçmesi için bunu yaz

 

 METODUN ÜSTÜNE BUNU YAZARSAN SWAGGER DE GÖZÜKMEZ

        [ApiExplorerSettings(IgnoreApi = true)]

 

 

public string replaceTurkish(string text)

        {

            var json = @"{""name"":"""+ text + @"""}";

            var name = JObject.Parse(json)["name"].ToString();

            return name.ToString();

        }

 

KULLANIMI

 

var name = replaceTurkish("Hills Young Sterilised Tavuklu K\u0131s\u0131rla\u015ft\u0131r\u0131lm\u0131\u015f Kedi Mamas\u0131 1.5 Kg")

 

 

TOKEN EKLEMEK

 

httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

 

*********************** 1 (Api2.cs) ************************

 

      public  HttpClient client;

      public  string username = "";

     public   string password = "";

      public string __VIEWSTATE = "";

      public string __EVENTVALIDATION = "";

      public string __VIEWSTATEGENERATOR = "";

 

       public CookieContainer cookies = new CookieContainer();

 

        public Api2(string username,string password)

        {

            this.username = username;

            this.password = password;

            ServicePointManager.Expect100Continue = true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookies;

            client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.29.2");

 

            client.Timeout = TimeSpan.FromMinutes(30);

 

        }

       

 public void viewStateYukle(string ilkSayfalink)

 {

     var ilkSayfaResponse = requestGet(ilkSayfalink);

 

     __VIEWSTATE = kes(ilkSayfaResponse, "id=\"__VIEWSTATE\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

     __EVENTVALIDATION = kes(ilkSayfaResponse, "id=\"__EVENTVALIDATION\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

     __VIEWSTATEGENERATOR = kes(ilkSayfaResponse, "id=\"__VIEWSTATEGENERATOR\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

 }

 

  public void viewStateYukleHtmlText(string responseHtml)

  {

 

      __VIEWSTATE = kes(responseHtml, "id=\"__VIEWSTATE\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

      __EVENTVALIDATION = kes(responseHtml, "id=\"__EVENTVALIDATION\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

      __VIEWSTATEGENERATOR = kes(responseHtml, "id=\"__VIEWSTATEGENERATOR\"", "/>").Replace("value=\"", "").Replace("\"", "").Trim();

  }

        public Api2()

        {

            ServicePointManager.Expect100Continue = true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            CookieContainer cookies = new CookieContainer();

            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookies;

            client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.29.2");

            client.Timeout = TimeSpan.FromMinutes(30);

 

        }

        public void apiSifirla()

        {

            return;

            CookieContainer cookies = new CookieContainer();

            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookies;

            client = new HttpClient(handler);

        }

        public string requestPost(string url, Dictionary<string, string> dict)

        {

            apiSifirla();

 

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

            var Content = new FormUrlEncodedContent(dict);

            HttpResponseMessage responseOtel = client.PostAsync(url, Content).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            return result;

        }

 

        public string requestPostJson(string url, object model)

        {

            apiSifirla();

 

            string json = JsonConvert.SerializeObject(model);

            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage responseOtel = client.PostAsync(url, stringContent).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            return result;

        }

 public string requestPostRawText(string url, string rawText)

 {

     apiSifirla();

     StringContent content = new StringContent(rawText, Encoding.UTF8, "text/plain");

     HttpResponseMessage response = client.PostAsync(url, content).Result;

     string result = response.Content.ReadAsStringAsync().Result;

     return result;

 }

 

public string requestPostJsonString(string url, string json)

        {

            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage responseOtel = client.PostAsync(url, stringContent).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            return result;

        }

 

        public string requestGet(string url)

        {

            apiSifirla();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

            HttpResponseMessage responseOtel = client.GetAsync(url).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            result = System.Net.WebUtility.HtmlDecode(result);

 

            return result;

        }

 

public string requestGetBase64(string apiKey, int carId)

        {

            string url = "resimurl";

 

            HttpResponseMessage response = client.GetAsync(url).Result;

            var result = response.Content.ReadAsByteArrayAsync().Result;

            return Convert.ToBase64String(result);

        }

 

 

 public string kes(string txt, string ilk, string son)

        {

            try

            {

                string parcali1 = (txt.Split(new string[] { ilk }, StringSplitOptions.None))[1];

                string parcali2 = (parcali1.Split(new string[] { son }, StringSplitOptions.None))[0];

                return parcali2.Trim();

            }

            catch (Exception)

            {

                return "";

            }

        }

 

        public List<string> kesList(string txt, string ilk, string son)

        {

            try

            {

                List<string> list = new List<string>();

                string[] parcali1 = (txt.Split(new string[] { ilk }, StringSplitOptions.None));

                for (int i = 1; i < parcali1.Length; i++)

                {

                    string parcali2 = (parcali1[i].Split(new string[] { son }, StringSplitOptions.None))[0];

                    list.Add(parcali2.Trim());

 

                }

                return list;

            }

            catch (Exception)

            {

                return null;

            }

        }

 

public string[] splits(string text,string split)

        {

            try

            {

                return text.Split(new string[] { split }, StringSplitOptions.None);

            }

            catch (Exception)

            {

            }

            return null;

        }

 

 List<string> otelKodList = new List<string>();

 

        public bool loginOl()

        {

            apiSifirla();

            otelKodList = new List<string>();

            try

            {

 

                Dictionary<string, string> dict = new Dictionary<string, string>();

                dict.Add("program", "html002");

                dict.Add("login", username);

                dict.Add("rolehidden", "HOTELLOCAL");

                dict.Add("password", password);

                dict.Add("language", "E");

                dict.Add("verzend", "Login");

 

                string htmlText = requestPost("https://www.jil.travel/", dict);

                string otelKod = kes(htmlText, "/generalproductid/", "\"");

                if (otelKod.Contains("/")) otelKod = otelKod.Split('/')[0].Trim();

                if (otelKod == "" || htmlText == "") return false;

 

                otelKodList.Add(otelKod);

 

            }

            catch (Exception ex)

            {

                return false;

            }

 

            return true;

 

        }

 

 

KULLANIMI

 

  Api2 api=new Api2();

        private void button1_Click(object sender, EventArgs e)

        {

            string test = api.requestGet("https://www.gratis.com/flormar-brow-micro-filler-pen-kas-doldurucu-kalem/urun/Flormar47000097?sku=10181329");

 

        }

 

 

PARAMETRESİZ POST GÖNDERME

 

public HttpResponseMessage mesajGonder(string tel, string mesaj)

        {

            try

            {

 

                string url ="apiurl";

                var request = new HttpRequestMessage(HttpMethod.Post, url);

                var response = client.SendAsync(request).Result;

 

                return response;

            }

            catch (Exception ex)

            {

                throw ex;

            }

 

        }

 

 

*********************** 2 ************************

 

 

 string json = JsonConvert.SerializeObject(model);

 var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

 GenelCevap results = JsonConvert.DeserializeObject<GenelCevap>(result);

 

 

// System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

bu sekilde header eklersin client.DefaultRequestHeaders.Add("token", token);

client.DefaultRequestHeaders.Add("x-requested-with", "XMLHttpRequest");

 

JsonConvert.SerializeObject(model, Formatting.Indented);// formatlarsan güzel gözükür word wrap yapar

 

  private void button1_Click(object sender, EventArgs e)

        {

            try

            {

                ServicePointManager.Expect100Continue = true;

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

 

                Kullanici kullanici = new Kullanici();

                kullanici.data.kullanici_ad = "ramazan";

                kullanici.data.kullanici_mail = "mustafa@gmail.com";

                kullanici.data.kullanici_sifre = "134";

                kullanici.table = "kullanici";

                kullanici.method = xenumGenel.insert;

  

                var json = JsonConvert.SerializeObject(kullanici);

                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

 

  CookieContainer cookies = new CookieContainer();

                HttpClientHandler handler = new HttpClientHandler();

                handler.CookieContainer = cookies;

                HttpClient client = new HttpClient(handler);

 

                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("aplication/json"));

                HttpResponseMessage response = client.PostAsync(xenumGenel.url, stringContent).Result;

 

                var byteArray = response.Content.ReadAsByteArrayAsync().Result;

                var result = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

                GenelCevap results = JsonConvert.DeserializeObject<GenelCevap>(result);

                textBox1.Text = results.@return+"\n"+results.msg;

            }

            catch (Exception ex)

            {

                textBox1.Text = ex.Message;

            }

        }

 

2-) DİĞER

 

  HttpClient client;

 

 private void Form1_Load(object sender, EventArgs e)

        {

            ServicePointManager.Expect100Continue = true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            CookieContainer cookies = new CookieContainer();

            HttpClientHandler handler = new HttpClientHandler();

            handler.CookieContainer = cookies;

            client = new HttpClient(handler);

 }

 

 public string requestPost(string url, Dictionary<string, string> dict)

        {

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

            var Content = new FormUrlEncodedContent(dict);

            HttpResponseMessage responseOtel = client.PostAsync(url, Content).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            return result;

        }

 

        public string requestPostJson(string url, object model)

        {

            string json = JsonConvert.SerializeObject(model);

            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage responseOtel = client.PostAsync(url, stringContent).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            return result;

        }

 

        public string requestGet(string url)

        {

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

            HttpResponseMessage responseOtel = client.GetAsync(url).Result;

            string result = responseOtel.Content.ReadAsStringAsync().Result;

            result = System.Net.WebUtility.HtmlDecode(result);

            return result;

        }

 

 

 

public void loginOl()

        {

            var dict = new Dictionary<string, string>();

            dict.Add("kullaniciAdi", "asd");

            dict.Add("sifre", "asd");

            string loginResponse = requestPost("https://ozerdemmotosiklet.com/Site/Giris", dict);

        }

 

2-) Resim Kaydetme

 

public void SaveImage(string filename, ImageFormat format, string imageUrl)

        {

            try

            {

                string name = Path.GetFileName(imageUrl);

                string[] allfiles = Directory.GetFiles(@"Resimler", "*.jpg", SearchOption.AllDirectories); // .txt veya .*

                foreach (var file in allfiles)

                {

                    FileInfo info = new FileInfo(file);

                    string fullname = info.Name.ToString();

                    if (name.Equals(fullname))

                    {

                        return;

                    }

                }

 

                WebClient client = new WebClient();

                Stream stream = client.OpenRead(imageUrl);

                Bitmap bitmap; bitmap = new Bitmap(stream);

                if (bitmap != null)

                {

                    bitmap.Save(filename, format);

                }

                stream.Flush();

                stream.Close();

                client.Dispose();

            }

            catch (Exception ex)

            {

 

            }

 

        }

 

 ** KULLANIMI **

 

SaveImage(resimYol, ImageFormat.Jpeg, "https://ozerdemmotosiklet.com/Resimler/" + item6.Resim1);

 

 

 2024 Mayıs 10 Cuma
 1,778