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

C#HttpWebRequest常用请求方式

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

在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请求常用的两种方式

相关推荐

「layui」表单验证:验证注册

注册界面手动验证获取短信验证码代码原文<!DOCTYPEhtml><htmllang="zh"><head>&...

Full text: Joint statement between China and Kenya on creating an inspiring example in the all-weather China-Africa community with a shared future for the new era

JointStatementBetweenthePeople'sRepublicofChinaandtheRepublicofKenyaonCreatinganInspi...

国际组织最新岗位信息送给你

国际刑警组织PostingTitleITLogisticsManagerGrade5DutyStationAbidjan,IvoryCoastDeadlineforApplicatio...

【新功能】Spire.PDF 8.12.5 支持设置表单域的可见与隐藏属性

Spire.PDF8.12.5已发布。该版本新增支持设置表单域的可见与隐藏属性、添加自定义的元数据以及给PDF文档的元数据添加新的命名空间。本次更新还增强了PDF到DOCX和图片的转换...

AI curbs show Biden&#39;s rejection of cooperation

AIcurbsshowBiden'srejectionofcooperation:ChinaDailyeditorial-Opinion-Chinadaily.com.cnT...

“煤气灯效应”上热搜,这几种有毒的“情感关系”也要注意了……

近日,“煤气灯效应”(theGaslightEffect)再次进入公众视野并登上热搜,引发网友广泛关注。那么,什么是“煤气灯效应”?以“爱”之名进行情绪控制在心理学中,通过“扭曲受害者眼中的真实”...

Qt编写推流程序/支持webrtc265/从此不用再转码/打开新世界的大门

一、前言在推流领域,尤其是监控行业,现在主流设备基本上都是265格式的视频流,想要在网页上直接显示监控流,之前的方案是,要么转成hls,要么魔改支持265格式的flv,要么265转成264,如果要追求...

写给运维的Nginx秘籍

要说Web服务器、代理服务器和调度服务器层面,目前使用最大的要数Nginx。对于一个运维工程师日常不可避免要和Nginx打交道。为了更好地使用和管理Nginx,本文就给大家介绍几个虫虫日常常用的秘籍。...

突破亚马逊壁垒,Web Unlocker API 助您轻松获取数据

在数据驱动决策的时代,电商平台的海量数据是十足金贵的。然而,像亚马逊这样的巨头为保护自身数据资产,构建了近乎完美的反爬虫防线,比如IP封锁、CAPTCHA验证、浏览器指纹识别,常规爬虫工具在这些防线面...

每日一库之 logrus 日志使用教程

golang日志库golang标准库的日志框架非常简单,仅仅提供了print,panic和fatal三个函数对于更精细的日志级别、日志文件分割以及日志分发等方面并没有提供支持.所以催生了很多第三方...

对比测评:为什么AI编程工具需要 Rules 能力?

通义灵码ProjectRules在开始体验通义灵码ProjectRules之前,我们先来简单了解一下什么是通义灵码ProjectRules?大家都知道,在使用AI代码助手的时候,有时...

python 面向对象编程

Python的面向对象编程(OOP)将数据和操作封装在对象中,以下是深度解析和现代最佳实践:一、核心概念重构1.类与实例的底层机制classRobot:__slots__=['...

Windows系统下常用的Dos命令介绍(一)

DOS是英文DiskOperatingSystem的缩写,意思是“磁盘操作系统”。DOS主要是一种面向磁盘的系统软件,说得简单些,DOS就是人给机器下达命令的集合,是存储在操作系统中的命令集。主要...

使用 Flask-Admin 快速开发博客后台管理系统:关键要点解析

一、为什么选择Flask-Admin?Flask-Admin是Flask生态中高效的后台管理框架,核心优势在于:-零代码生成CRUD界面:基于数据库模型自动生成增删改查功能-高度可定制...

Redis淘汰策略导致数据丢失?

想象一下,你的Redis服务器是一个合租宿舍,内存就是床位。当新数据(新室友)要住进来,但床位已满时,你作为宿管(淘汰策略)必须决定:让谁卷铺盖走人?Redis提供了8种"劝退"方案,...