C# HttpWebRequest详解:GET与POST请求实现及中文乱码解决

阿澈
阿澈
发布时间:2026-10-14| 4人浏览过
原创

在C#开发中,HttpWebRequest是进行底层HTTP协议交互的核心类。它支持通过GET和POST两种方式获取服务器数据或提交信息。针对实际应用中常见的中文参数传递导致乱码、以及需要携带Cookie保持登录状态等场景,本文详细解析关键配置参数并提供可直接运行的代码模板。

核心原理与准备条件

HttpWebRequest基于HTTP协议,主要用于与Web服务器进行双向数据交换。
在使用前需确保引入必要的命名空间:
- System.Net:包含HttpWebRequest、HttpWebResponse和CredentialCache等网络类。
- System.IO:用于处理输入输出流(Stream)和读取响应内容。
- System.Text:用于字符编码转换,特别是解决中文乱码问题。

第1步:使用GET方式请求数据

GET请求适合获取公开资源,其特点是将参数附加在URL地址栏中(例如?key=value),对长度有限制且明文可见。

1.1 基础GET请求

目的:向指定URL发送不带参数的GET请求并获取返回文本。

操作:

using System;
using System.Net;
using System.IO;

public void GetSimpleRequest()
{
    // 1. 创建请求对象
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.example.com/api");
    
    // 2. 设置请求方法为GET
    req.Method = "GET";
    
    // 3. 发送请求并获取响应
    using (WebResponse wr = (HttpWebResponse)req.GetResponse())
    {
        using (StreamReader sr = new StreamReader(wr.GetResponseStream()))
        {
            string content = sr.ReadToEnd();
            Console.WriteLine(content);
        }
    }
}

1.2 GET方式处理中文参数(含乱码修复)

目的:解决URL中包含中文时,因编码不匹配导致的400错误或乱码。

入口:构建带有Query String的URL。

动作:使用HttpUtility.UrlEncode对中文进行转义。注意编码格式(如utf-8或gb2312)必须与服务端要求一致。

using System.Web; // 需要引用System.Web程序集
using System.Text;
using System.Net;

public void GetWithChineseParams()
{
    string keyword = "中文搜索";
    // 使用UTF8编码进行URL编码
    string encodedParam = HttpUtility.UrlEncode(keyword, Encoding.UTF8);
    
    string url = $"https://www.example.com/search?q={encodedParam}";
    
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
    req.Method = "GET";
    
    using (WebResponse wr = req.GetResponse())
    {
        // 处理响应流...
    }
}

第2步:使用POST方式提交数据

POST请求将数据放在请求体(Body)中,适合传输表单数据、文件较大或包含敏感信息的场景。

2.1 基础POST请求

目的:向服务器提交键值对形式的数据。

重要参数: - ContentType:通常为application/x-www-form-urlencoded。 - ContentLength:必须以字节为单位设置。

using System.IO;
using System.Net;
using System.Text;

public void PostFormData()
{
    string postData = "hl=zh-CN&newwindow=1";
    byte[] bs = Encoding.ASCII.GetBytes(postData); // ASCII仅适用于纯英文符号
    
    HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.example.com/submit");
    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    req.ContentLength = bs.Length;
    
    // 写入请求体
    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(bs, 0, bs.Length);
    }
    
    using (WebResponse wr = req.GetResponse())
    {
        // 处理响应...
    }
}

2.2 POST方式处理中文参数

风险提示:直接使用ASCII编码会导致中文变为乱码甚至报错。必须先编码参数,并在Header中告知服务端编码类型。

操作:使用UrlEncode对中文字符转义,并修改ContentType增加charset属性。

string key = "参数一";
string val = "中文值";
Encoding myEncoding = Encoding.UTF8;

// 构造参数字符串
string param = $"{HttpUtility.UrlEncode(key, myEncoding)}={HttpUtility.UrlEncode(val, myEncoding)}&param2=val2";
byte[] postBytes = Encoding.UTF8.GetBytes(param); // 注意此处用UTF8获取字节数组

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.example.com/submit");
req.Method = "POST";
// 声明服务端解析使用的编码
req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
req.ContentLength = postBytes.Length;

using (Stream stream = req.GetRequestStream())
{
    stream.Write(postBytes, 0, postBytes.Length);
}
// 后续获取Response... 

第3步:高级配置:Cookie管理

许多网站需要登录后才能访问,或者需要维持Session。此时必须配置CookieContainer。

动作:

  1. 创建CookieContainer对象。
  2. 将其赋值给HttpWebRequest.CookieContainer属性。
  3. 若需模拟已有Cookie,可使用SetCookies方法注入。
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.example.com/login");
req.Method = "POST";

// 1. 实例化容器并关联到请求
CookieContainer cookieJar = new CookieContainer();
req.CookieContainer = cookieJar;

// ... 其他配置 ...

// 如果已有cookie字符串,可以这样添加:
// Uri uri = new Uri("https://www.example.com");
// cookieJar.SetCookies(uri, "sid=abc123; token=xyz789");

第4步:封装通用请求工具类

为了提高复用性,建议将上述逻辑封装为一个静态类。以下是一个包含Get/Post方法及自动编码处理的简化版结构示例:

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace HttpHelper
{
    public static class HttpHelper
    {
        /// <summary>
        /// 发起GET请求
        /// </summary>
        public static string GetHtml(string url, string encoding = "utf-8")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            // 可在此处设置 UserAgent, Referer 等
            
            try
            {
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                throw new Exception($"GET请求失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 发起POST请求
        /// </summary>
        public static string PostHtml(string url, string data, string contentType,
                                      string encodingName = "utf-8", CookieContainer cookies = null)
        {
            byte[] bytes = Encoding.GetEncoding(encodingName).GetBytes(data);
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.ContentLength = bytes.Length;
            if (cookies != null) request.CookieContainer = cookies;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encodingName)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                // 在生产环境中,建议记录错误日志而不是直接抛出
                throw new Exception($"POST请求失败: {ex.Message}");
            }
        }
    }
}

完成判断与排错

  • 验证成功:代码运行无异常,能打印出服务端预期的HTML或JSON文本。
  • 常见错误排查:
    • ProtocolError (4xx/5xx):检查URL拼写、权限或服务器状态。
    • Timeout:默认超时较长,可通过request.Timeout = 5000;优化,或检查网络连通性。
    • ContentLength required:POST请求必须严格设置ContentLength,否则服务端可能拒绝接收。

简要总结

C#中的HttpWebRequest虽然API设计较为传统(相比现代HttpClient),但依然稳定可控。关键在于正确设置Method、ContentType,处理中文时需统一编码标准(推荐UTF-8),复杂场景下务必维护好CookieContainer的状态。以上就是C#中HttpWebRequest的详细用法介绍,更多关于C#网络编程的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。