在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C# 接口的Get、Post、WebService请求方法一览,值得收藏 public static class HttpHelper { const string DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 4.0.30319)"; const string DEFAULT_CONTENT_TYPE = "application/json"; #region Http Get Method /// <summary> /// GET请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string Get(string url) { return Get(url, null); } /// <summary> /// GET请求,可以添加自定义的Header信息 /// </summary> /// <returns></returns> public static string Get(string url, IDictionary<string, string> headerList) { var request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = DEFAULT_USER_AGENT; request.ContentType = DEFAULT_CONTENT_TYPE; if (headerList != null) { foreach (var header in headerList) { request.Headers.Add(header.Key, header.Value); } } var responseStream = request.GetResponse().GetResponseStream(); using (var reader = new StreamReader(responseStream)) { var result = reader.ReadToEnd(); responseStream.Close(); return result; } } #endregion /// <summary> /// POST请求 /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <param name="contentType"></param> /// <returns></returns> public static string Post(string url, string postData, string contentType = DEFAULT_CONTENT_TYPE) { var webClient = new WebClient(); webClient.Headers.Add("user-agent", DEFAULT_USER_AGENT); webClient.Headers.Add("Content-Type", contentType); byte[] sendData = Encoding.UTF8.GetBytes(postData); byte[] responseData = webClient.UploadData(url, "POST", sendData); return Encoding.UTF8.GetString(responseData); } /// <summary> /// POST请求,并可以传入Header信息 /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <param name="headParams"></param> /// <returns></returns> public static string Post(string url, string postData, IDictionary<string, string> headParams) { var webClient = new WebClient(); webClient.Headers.Add("user-agent", DEFAULT_USER_AGENT); webClient.Headers.Add("Content-Type", DEFAULT_CONTENT_TYPE); if (headParams != null && headParams.Count > 0) { foreach (var item in headParams) { if (webClient.Headers.AllKeys.Contains(item.Key)) { webClient.Headers.Remove(item.Key); } webClient.Headers.Add(item.Key, item.Value); } } byte[] sendData = Encoding.UTF8.GetBytes(postData); byte[] responseData = webClient.UploadData(url, "POST", sendData); return Encoding.UTF8.GetString(responseData); } /// <summary> /// HTTP Post请求,可以传入Header信息和超时限制 /// </summary> /// <param name="url"></param> /// <param name="content"></param> /// <param name="headParams"></param> /// <param name="timeout"></param> /// <returns></returns> public static string HttpPost(string url, string content,string ContentType, IDictionary<string, string> headParams,int timeout) { try { string result = string.Empty; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = ContentType; if (headParams != null && headParams.Count > 0) { foreach (var item in headParams) { if (req.Headers.AllKeys.Contains(item.Key)) { req.Headers.Remove(item.Key); } req.Headers.Add(item.Key, item.Value); } } byte[] data = Encoding.UTF8.GetBytes(content); req.ContentLength = data.Length; req.Timeout = timeout * 1000; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; } catch (Exception ex) { throw ex; } } /// <summary> /// 需要WebService支持Get调用 /// </summary> public static string WebServiceGet(String url, String methodname, Hashtable pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + "/" + methodname + "?" + HashtableToPostData(pars)); request.Method = "GET"; request.ContentType = "application/x-www-form-urlencoded"; // 凭证 request.Credentials = CredentialCache.DefaultCredentials; //超时时间 request.Timeout = 10000; var response = request.GetResponse(); var stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream, Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); return retXml; } /// <summary> /// 需要WebService支持Post调用 /// </summary> public static string PostWebServiceByJson(String url, String methodname, Hashtable pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + "/" + methodname); request.Method = "POST"; request.ContentType = "application/json;charset=utf-8"; request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; byte[] data = Encoding.UTF8.GetBytes(HashtableToPostData(pars)); request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8); string retXml = sr.ReadToEnd(); sr.Close(); return retXml; } /// <summary> /// http Post调用 WebService /// </summary> public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Credentials = CredentialCache.DefaultCredentials; request.Timeout = 10000; #region 参数拼接成字符串,最后编码 StringBuilder sb = new StringBuilder(); foreach (string k in Pars.Keys) { if (sb.Length > 0) { sb.Append("&"); } sb.Append( HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()) ); } byte[] data = Encoding.UTF8.GetBytes(sb.ToString()); #endregion #region 把编码后的参数写入请求流中 request.ContentLength = data.Length; Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); #endregion #region 读取结果,创建XmlDocument对象,对象加载结果 var response = request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); String retXml = sr.ReadToEnd(); sr.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(retXml); #endregion return doc; } private static String HashtableToPostData(Hashtable ht) { StringBuilder sb = new StringBuilder(); foreach (string k in ht.Keys) { if (sb.Length > 0) { sb.Append("&"); } sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(ht[k].ToString())); } return sb.ToString(); } }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论