C# HttpWebRequest实现http Get和Post请求

在C#中用来提取网页Html的组件比较多,常用的用WebBrowser、WebClient、HttpWebRequest这三个。下面简单介绍以下HttpWebRequest实现Get和Post请求。

Http post code demo:

public string HttpPost(string postUrl, string paramData, Encoding dataEncode)
{
    string result = string.Empty;

    //Define a HttpWebRequest object
    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
    webReq.Method="POST";
    webReq.ContentType="application/x-www-form-urlencoded";

    //先将post的参数写入HttpWebRequest
    byte[] byteArray = dataEncode.GetBytes(paramData);
    webReq.ContentLength = byteArray.Length;
    Stream newStream = webReq.GetRequestStream();
    newStream.Write(byteArray, 0, byteArray.Length);
    newStream.Close();

    //提交Post请求,并获取数据
    HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
    StreamReader sReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    result = sReader.ReadToEnd();
    sReader.Close();
    response.Close();
    newStream.Close();

    return result;
}

Http Get code demo:

public string HttpGet(string getUrl, string paramData, Encoding dataEncode)
{
    string result = string.Empty;
    
    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(getUrl +"?"+ paramData));
    webReq.Method = "GET";
    webReq.ContentType = "text/html";

    HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
    StreamReader sReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    result = sReader.ReadToEnd();
    sReader.Close();
    response.Close();

    return result;
}