//using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; namespace Utility.Extra { public class HttpHelper { private static HttpWebRequest GetHttpWebRequest(string url, Dictionary headerDic, string method) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = method; if(headerDic != null && headerDic.Count > 0) { foreach(var h in headerDic) { request.Headers.Add(h.Key, h.Value); } } return request; } private static string GetUrlParamString(Dictionary paramDic) { StringBuilder sb = new StringBuilder(); if(paramDic == null || paramDic.Count() < 1) { return string.Empty; } foreach(var d in paramDic) { if(sb.Length < 1) { sb.AppendFormat("{0}={1}", d.Key, d.Value); } else { sb.AppendFormat("&{0}={1}", d.Key, d.Value); } } sb.Insert(0, "?"); return sb.ToString(); } private static string GetResponseString(HttpWebRequest request) { try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } } catch (WebException ex) { throw ex; } } public static string DoPost(string url, string jsonData, Dictionary headerDic = null) { var request = GetHttpWebRequest(url, headerDic, "POST"); request.ContentType = "application/json"; request.ContentLength = 0; if(!string.IsNullOrWhiteSpace(jsonData)) { byte[] buffer = Encoding.UTF8.GetBytes(jsonData); request.ContentLength = buffer.Length; try { request.GetRequestStream().Write(buffer, 0, buffer.Length); } catch(WebException ex) { throw ex; } } try { return GetResponseString(request); } catch (WebException ex) { throw ex; } } } }