在C#中使用HttpWebRequest类是用于发送HTTP请求的类,它属于System.Net命名空间。通过HttpWebRequest,你可以使用不同的请求方法(例如GET、POST、PUT、DELETE等)来与Web服务器进行交互。1. GET请求
GET请求通常用于请求服务器上的数据,不修改服务器上的资源。
引用
using System.IO;using System.Net;using System.Threading.Tasks;
//直接返回字符串public static string HttpGet(string url){	Encoding encoding = Encoding.UTF8;	HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);	request.Method = "GET";	request.Accept = "text/html, application/xhtml+xml, */*";	request.ContentType = "application/json";	HttpWebResponse response = (HttpWebResponse)request.GetResponse();	using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))	{		return reader.ReadToEnd();	}}
// 直接读取文件流public static string HttpGet(string url){    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);    req.Method = "Get";    try    {        using (WebResponse wr = req.GetResponse())        {            HttpWebResponse response = wr as HttpWebResponse;            Stream stream = response.GetResponseStream();            //读取到内存            MemoryStream ms = new MemoryStream();            byte[] buffer = new byte[1024];            while (true)            {                int sz = stream.Read(buffer, 0, 1024);                if (sz == 0) break;                ms.Write(buffer, 0, sz);            }            string content = Convert.ToBase64String(ms.ToArray());            return content;        }    }    catch (Exception ex)    {        return null;    }}
2. POST请求
POST请求通常用于向服务器提交数据,如表单数据或JSON数据。
application/json
//Postpublic static string HttpPost(string url, string body){	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();	}}
application/x-www-form-urlencoded
public static string PostUrlFormUrlencoded(string url, string postData){    string result = "";    try    {        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        
        byte[] data = Encoding.UTF8.GetBytes(postData);
        req.ContentLength = data.Length;
        using (Stream reqStream = req.GetRequestStream())        {            reqStream.Write(data, 0, data.Length);
            reqStream.Close();        }
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream stream = resp.GetResponseStream();
        //获取响应内容        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))        {            result = reader.ReadToEnd();        }    }    catch (Exception e)    {        Console.WriteLine("发送请求出错:" + e.Message);    }
    return result;}
multipart/form-data
public static string HttpPost(string url, NameValueCollection kVDatas = null, JObject headers = null,    string method = WebRequestMethods.Http.Post, int timeOut = -1){    try    {        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");        byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");        byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);        request.ContentType = "multipart/form-data; boundary=" + boundary;        request.Method = "POST";        request.KeepAlive = true;        request.Timeout = timeOut;        if (headers != null)        {            IEnumerable<JProperty> properties = headers.Properties();            foreach (JProperty item in properties)            {                request.Headers.Add(item.Name, item.Value.ToString());            }        }
        CredentialCache credentialCache = new CredentialCache        {            { new Uri(url), "Basic", new NetworkCredential("member", "secret") }        };        request.Credentials = credentialCache;
        request.ServicePoint.Expect100Continue = false;        using (Stream stream = request.GetRequestStream())        {            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";            if (kVDatas != null)            {                foreach (string key in kVDatas.Keys)                {                    stream.Write(boundarybytes, 0, boundarybytes.Length);                    string formitem = string.Format(formdataTemplate, key, kVDatas[key]);                    byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);                    stream.Write(formitembytes, 0, formitembytes.Length);                }            }            stream.Write(endbytes, 0, endbytes.Length);        }        HttpWebResponse response = (HttpWebResponse)request.GetResponse();        using (StreamReader stream = new StreamReader(response.GetResponseStream()))        {            return stream.ReadToEnd();        }
    }    catch (Exception e)    {
        Console.WriteLine(e.Message);        return e.Message;    }}
上传文件
public static string HttpUploadFile(string url, string filePath, string fileName, string paramName, string contentType,    NameValueCollection nameValueCollection){    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);    request.ContentType = "multipart/form-data; boundary=" + boundary;    request.Method = "POST";    request.KeepAlive = true;    request.Credentials = CredentialCache.DefaultCredentials;    Stream requestStream = request.GetRequestStream();    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";    foreach (string key in nameValueCollection.Keys)    {        requestStream.Write(boundarybytes, 0, boundarybytes.Length);        string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);        requestStream.Write(formitembytes, 0, formitembytes.Length);    }    requestStream.Write(boundarybytes, 0, boundarybytes.Length);    string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", paramName, fileName, contentType);    byte[] headerbytes = Encoding.UTF8.GetBytes(header);    requestStream.Write(headerbytes, 0, headerbytes.Length);    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);    byte[] buffer = new byte[4096];    int bytesRead = 0;    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)    {        requestStream.Write(buffer, 0, bytesRead);    }    fileStream.Close();    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");    requestStream.Write(trailer, 0, trailer.Length);    requestStream.Close();    WebResponse webResponse = null;    try    {        webResponse = request.GetResponse();        Stream responseStream = webResponse.GetResponseStream();        StreamReader streamReader = new StreamReader(responseStream);        string result = streamReader.ReadToEnd();        return result;    }    catch (Exception ex)    {        if (webResponse != null)        {            webResponse.Close();            webResponse = null;        }        return null;    }    finally    {        request = null;    }}
3. PUT请求
PUT请求用于上传文件或修改服务器上的资源。
public static void HttpPUT(){	HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data");	request.Method = "PUT";	request.ContentType = "application/json"; // 或者其他适当的MIME类型,如 "text/xml" 或 "image/jpeg" 等
	using (var postData = new StreamWriter(request.GetRequestStream()))	{		postData.Write(JsonConvert.SerializeObject(new { key1 = "value1", key2 = "value2" })); // 发送JSON数据示例	}
	using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())	{		using (Stream responseStream = response.GetResponseStream())		{			using (StreamReader reader = new StreamReader(responseStream))			{				string responseText = reader.ReadToEnd();				Console.WriteLine(responseText);			}		}	}}
4. DELETE请求
DELETE请求用于请求删除指定的资源。
public static void HttpDELETE(){	HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data/123"); 	request.Method = "DELETE";	using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())	{		Console.WriteLine("Resource deleted with status: " + response.StatusCode);	}}
C# HttpClient四种常用请求数据格式
C#调用WebApi请求常用的两种方式
阅读原文:原文链接
该文章在 2025/2/17 13:06:35 编辑过