C#的WebRequest类

C#的WebRequest类是一个抽象基类,用于发送 Web 请求并与远程服务器进行交互。它提供了许多方法和属性来配置和执行 HTTP 请求。

下面是使用WebRequest类发送简单的 HTTP GET 请求的示例:

string url = "https://api.example.com/data";
WebRequest request = WebRequest.Create(url);
request.Method = "GET";

using (WebResponse response = request.GetResponse())
{
    using (Stream dataStream = response.GetResponseStream())
    {
        using (StreamReader reader = new StreamReader(dataStream))
        {
            string responseContent = reader.ReadToEnd();
            Console.WriteLine(responseContent);
        }
    }
}

这个示例中,我们首先创建一个WebRequest对象,并设置请求的 URL 和请求方法为 GET。然后,使用GetResponse()方法获取服务器的响应。

通过获取响应对象的GetResponseStream()方法,我们可以获得响应的数据流。然后,我们使用StreamReader读取数据流,并将响应内容作为字符串打印出来。

需要注意的是,在使用完WebResponseStreamStreamReader后,我们使用using语句来确保资源的正确释放。

除了发送简单的 GET 请求,WebRequest类还提供了其他方法和属性,可以用于发送 POST 请求、设置请求头、处理响应等操作。

MESHelper基于WebRequest实现发送Web请求并得到Respond数据

public static string HttpRequest(string url, string body, int timeout = 60000,
            HttpEncoding encoding = HttpEncoding.UTF8,
            HttpMethod method = HttpMethod.POST,
            HttpContentType contenttype = HttpContentType.Form)
{
    // 检查服务器地址和发送数据是否为空
    if (String.IsNullOrWhiteSpace(url))
    {
        throw new ArgumentNullException("server url can't be empty...");
    }

    if (String.IsNullOrWhiteSpace(body))
    {
        throw new ArgumentNullException("send body can't be empty...");
    }

    HttpWebRequest request = null;

    try
    {
        // 根据请求方法创建 HttpWebRequest 对象
        if (method == HttpMethod.POST)
            request = (HttpWebRequest)WebRequest.Create(url);
        else
            request = (HttpWebRequest)WebRequest.Create(body);

        // 设置超时时间
        if (timeout != 0)
        {
            request.Timeout = timeout;
            request.ReadWriteTimeout = timeout;
        }

        request.Method = method.ToString();

        // 设置内容类型
        switch (contenttype)
        {
            case HttpContentType.Form:
                request.ContentType = "application/x-www-form-urlencoded";
                break;
            case HttpContentType.Json:
                request.ContentType = "application/json";
                break;
            case HttpContentType.Xml:
                request.ContentType = "application/xml";
                break;
            case HttpContentType.Text:
                request.ContentType = "text/plain";
                break;
            default:
                request.ContentType = "application/x-www-form-urlencoded";
                break;
        }

        // 添加请求到缓存列表
        lock (gHttpCache)
        {
            gHttpCache.Add(request);
        }

        var encod = GetEncoding(encoding);
        if (method == HttpMethod.POST)
        {
            // 将数据转换为字节数组并设置请求内容长度
            byte[] buffer = encod.GetBytes(body);
            request.ContentLength = buffer.Length;
            using (var stream = request.GetRequestStream())
            {
                // 发送请求数据
                stream.Write(buffer, 0, buffer.Length);
            }
        }

        // 发送请求并获取响应
        var response = (HttpWebResponse)request.GetResponse();
        System.IO.Stream s = response.GetResponseStream();
        if (s != null)
        {
            var reader = new System.IO.StreamReader(s, encod);
            // 读取响应数据
            string responseString = reader.ReadToEnd();
            s.Close();
            reader.Close();

            return responseString;
        }

        return String.Empty;
    }
    catch (Exception ex)
    {
        // 捕获异常并返回异常信息
        return ex.ToString();
    }
    finally
    {
        if (request != null)
        {
            // 从缓存列表中移除请求
            lock (gHttpCache)
            {
                gHttpCache.Remove(request);
            }
        }
    }
}

这是一个用于发送 HTTP 请求的方法。它接受以下参数:

  • url:请求的 URL 地址。
  • body:请求体,即需要发送的数据。
  • timeout:超时时间,默认为 60000 毫秒。
  • encoding:请求和响应的编码方式,默认为 UTF-8。
  • method:请求方法,默认为 POST。
  • contenttype:请求的内容类型,默认为表单形式。

方法首先检查 URL 和请求体是否为空,然后根据提供的参数创建一个HttpWebRequest对象。如果指定了超时时间,设置请求的超时时间和读写超时时间。

根据请求方法和内容类型,设置请求的方法和内容类型头。默认情况下,内容类型为application/x-www-form-urlencoded

接下来,根据指定的编码方式获取编码对象,并根据请求方法进行相应的处理。对于 POST 请求,将请求体转换为字节数组,并设置请求的内容长度和请求流。然后,获取服务器的响应,并将响应内容读取为字符串。

最后,返回响应字符串。如果发生异常,捕获异常并返回异常信息。

在方法的最后,通过finally块确保正确地从缓存中移除请求对象。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值