using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace ZB.QueueSys.Common { public class WebApiHelper { //定义一个用于保存静态变量的实例 private static WebApiHelper instance = null; //定义一个保证线程同步的标识 private static readonly object locker = new object(); //构造函数为私有,使外界不能创建该类的实例 private WebApiHelper() { } public static WebApiHelper Instance { get { if (instance == null) { lock (locker) { if (instance == null) instance = new WebApiHelper(); } } return instance; } } public string HttpGet(string url) { //string ss = HttpGet("http://localhost:000/api/Demo/GetXXX?Name=北京"); //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string str = reader.ReadToEnd(); return str; } } public string HttpPost(string url, string body) { //string ss = HttpPost("http://localhost:000/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}"); //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } } }
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!