编程语言
首页 > 编程语言> > C# HttpPost HttpGet

C# HttpPost HttpGet

作者:互联网

 public static string HttpPost(string url, string body)
       {

           //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();
           }
       }

       /// <summary>
       /// 请求网络资源,返回响应的文本
       /// </summary>
       /// <param name="Url">地址</param>
       /// <param name="postDataStr">参数</param>
       /// <returns></returns>
       public static string HttpGet(string Url, string postDataStr)
       {
           HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
           request.Method = "GET";
           //request.ContentType = "text/html;charset=UTF-8"; 
           request.ContentType = "application/json;charset=UTF-8";
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
           Stream myResponseStream = response.GetResponseStream();
           StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
           string retString = myStreamReader.ReadToEnd();
           myStreamReader.Close();
           myResponseStream.Close();
           return retString;
       }

 

标签:HttpGet,string,C#,request,HttpWebResponse,buffer,HttpPost,HttpWebRequest,respons
来源: https://www.cnblogs.com/wangxlei/p/15830241.html