C Simple example of http emulating post or get requests

  • 2021-10-13 08:25:01
  • OfStack


private string HttpPost(string Url, string postDataStr) 
    { 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
      request.Method = "POST"; 
      request.ContentType = "application/x-www-form-urlencoded"; 
      request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); 
      request.CookieContainer = cookie; 
      Stream myRequestStream = request.GetRequestStream(); 
      StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); 
      myStreamWriter.Write(postDataStr); 
      myStreamWriter.Close(); 
 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
 
      response.Cookies = cookie.GetCookies(response.ResponseUri); 
      Stream myResponseStream = response.GetResponseStream(); 
      StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 
      string retString = myStreamReader.ReadToEnd(); 
      myStreamReader.Close(); 
      myResponseStream.Close(); 
 
      return retString; 
    } 
 
    public string HttpGet(string Url, string postDataStr) 
    { 
      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.GetEncoding("utf-8")); 
      string retString = myStreamReader.ReadToEnd(); 
      myStreamReader.Close(); 
      myResponseStream.Close(); 
 
      return retString; 
    }

Sometimes cookie is used when post, like sending cookie when logging in to 163 to send an email, so save CookieContainer cookie = new CookieContainer () at any time in an external cookie attribute;

Note: Sometimes the request will be redirected, but we need to get something from the redirected url, such as QQ getting sid after successful login, but the above will automatically jump according to the redirected address. We can use:

request. AllowAutoRedirect = false; By setting redirection disabled, you can get the redirection address from the Location property of headers


Related articles: