百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

C#HttpWebRequest常用请求方式

zhezhongyun 2025-03-10 22:29 84 浏览

在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

//Post
public 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";


        //req.Timeout = 8000;//请求超时时间


        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 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"); // 假设删除ID为123的资源
	request.Method = "DELETE";
	using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
	{
		Console.WriteLine("Resource deleted with status: " + response.StatusCode);
	}
}

C# HttpClient四种常用请求数据格式

C#调用WebApi请求常用的两种方式

相关推荐

Go语言标准库中5个被低估的强大package

在Go语言的世界里,开发者们往往对fmt、net/http这些“明星包”耳熟能详,却忽略了标准库里藏着的一批“宝藏工具”。它们功能强大却低调内敛,能解决并发控制、内存优化、日志管理等核心问题。今天就带...

作为测试人,如何优雅地查看Log日志?

作为一名测试工程师,测试工作中和Linux打交道的地方有很多。比如查看日志、定位Bug、修改文件、部署环境等。项目部署在Linux上,如果某个功能发生错误,就需要我们去排查出错的原因,所以熟练地掌握查...

Java 从底层与接口实现了解String、StringBuffer、StringBuilder

String、StringBuffer和StringBuilder的接口实现关系:String:字符串常量,字符串长度不可变。Java中String是immutable(不可变)的。用于存放字符...

FluentData 从入门到精通:C#.NET 数据访问最佳实践

简介FluentData是一个微型ORM(micro-ORM),主打「FluentAPI」风格,让开发者在保持对原生SQL完全控制的同时,享受链式调用的便捷性。它与Dapper、Massi...

团队协作-代码格式化工具clang-format

环境:clang-format:10.0.0前言统一的代码规范对于整个团队来说十分重要,通过git/svn在提交前进行统一的ClangFormat格式化,可以有效避免由于人工操作带来的代码格式问题。C...

C# 数据操作系列 - 15 SqlSugar 增删改查详解(超长篇)

0.前言继上一篇,以及上上篇,我们对SqlSugar有了一个大概的认识,但是这并不完美,因为那些都是理论知识,无法描述我们工程开发中实际情况。而这一篇,将带领小伙伴们一起试着写一个能在工程中使用的模...

Mac OS 下 Unix 使用最多的100条命令(收藏级)

MacOS内置基于Unix的强大终端(Terminal),对开发者、运维工程师和日常用户来说,掌握常用的Unix命令是提升效率的关键。本文整理了100条在MacOS下最常用的U...

C语言字符串操作总结大全(超详细)

C语言字符串操作总结大全(超详细)1)字符串操作strcpy(p,p1)复制字符串strncpy(p,p1,n)复制指定长度字符串strcat(p,p1)附加字符串strncat...

经常使用到开源的MySQL,今天我们就来系统地认识一下

作为程序员,我们在项目中会使用到许多种类的数据库,根据业务类型、并发量和数据要求等选择不同类型的数据库,比如MySQL、Oracle、SQLServer、SQLite、MongoDB和Redis等。今...

电脑蓝屏代码大全_电脑蓝屏代码大全及解决方案

0X0000000操作完成0X0000001不正确的函数0X0000002系统找不到指定的文件0X0000003系统找不到指定的路径0X0000004系统无法打开文件0X0000005拒绝...

8个增强PHP程序安全的函数_php性能优化及安全策略

安全是编程非常重要的一个方面。在任何一种编程语言中,都提供了许多的函数或者模块来确保程序的安全性。在现代网站应用中,经常要获取来自世界各地用户的输入,但是,我们都知道“永远不能相信那些用户输入的数据”...

css优化都有哪些优化方案_css性能优化技巧

CSS优化其实可以分成几个层面:性能优化、可维护性优化、兼容性优化以及用户体验优化。这里我帮你梳理一份比较系统的CSS优化方案清单,方便你参考:一、加载性能优化减少CSS文件体积压缩CSS...

筹划20年,他终于拍成了这部电影_筹划20年,他终于拍成了这部电影英语

如果提名好莱坞最难搞影星,你第一时间会联想到谁?是坏脾气的西恩·潘,还是曾因吸毒锒铛入狱的小罗伯特·唐尼,亦或是沉迷酒精影响工作的罗素·克劳?上述大咖,往往都有着这样或那样的瑕疵。可即便如此,却都仍旧...

Keycloak Servlet Filter Adapter使用

KeycloakClientAdapters简介Keycloakclientadaptersarelibrariesthatmakeitveryeasytosecurea...

一些常用的linux常用的命令_linux常用命令有哪些?

在Linux的世界里,命令是与系统交互的基础。掌握常用命令不仅能让你高效地管理文件、进程和网络,还能为你进一步学习系统管理和自动化打下坚实的基础。本文将深入探讨一些最常用且功能强大的Linux...