C#(Winform) Http 发送数据

时间:2021-10-08 17:31:02

Get方式

 private string HttpGet(string url, string postData) {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (postData == "" ? "" : "?") + postData);
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;
}

Post方式

private string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded"; byte[] data = Encoding.GetEncoding("utf-8").GetBytes(postDataStr); request.ContentLength = data.Length; Stream myRequestStream = request.GetRequestStream(); myRequestStream.Write(data,,data.Length);
myRequestStream.Close(); 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;
}