C# Get和Post请求与响应

Get请求
    
        public static string HttpGet(string Url, string postDataStr)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url+(postDataStr == "" ? "" : "?")+postDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        } 
方法调用HttpGet("http://xx.xx.com/API/Login", "json={\"account\":\"test002\",\"passwd\":\"pwd002\"}");

Post请求
 /// <summary> 
 /// POST请求与获取结果 
 /// </summary> 
 public static string HttpPost(string Url, string postDataStr)
 {
     try
     {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
         request.Method = "POST";
         request.ContentType = "application/x-www-form-urlencoded";
         request.ContentLength = postDataStr.Length;
         StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
         writer.Write(postDataStr);
         writer.Flush();
         writer.Close();
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         string encoding = response.ContentEncoding;
         if (encoding == null || encoding.Length < 1)
         {
             encoding = "UTF-8"; //默认编码 
         }
         StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
         string retString = reader.ReadToEnd();
         reader.Close();
         return retString;
     }
     catch (Exception ex)
     {
         return ex.Message;
     }

 }
方法调用HttpPost("http://xx.xx.com/API/Login", "json={\"account\":\"test002\",\"passwd\":\"pwd002\"}");
转载请保留http://www.luofenming.com/show.aspx?id=ART2019111400001

评论