C#转发Post请求,包括参数和文件

本文详细介绍了一种转发HTTP POST请求的方法,通过读取当前请求的数据,构造新的POST请求并将其发送到指定URL,最后返回响应结果。该过程涉及读取请求流、设置请求头和转发数据等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        /// <summary>
        /// 转发Post请求
        /// </summary>
        /// <param name="curRequest">要转发的请求</param>
        /// <param name="url">转发到的Url地址</param>
        public static string ForwardRequest(HttpRequest curRequest, string url)
        {
            byte[] inputBytes;
            int inputStreamLength;
            using (var inputStream = curRequest.InputStream)
            {
                inputStreamLength = Convert.ToInt32(inputStream.Length);
                inputBytes = new byte[inputStreamLength + 1];
                inputStream.Read(inputBytes, 0, inputStreamLength);
                inputStream.Close();
            }

            //构造请求
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = curRequest.ContentType;
            request.ContentLength = curRequest.ContentLength;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(inputBytes, 0, inputStreamLength);
                requestStream.Close();
            }

            string result = string.Empty;
            using (WebResponse response = request.GetResponse())
            {
                if (response != null)
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                }
            }

            return result;
        }

 

转载于:https://www.cnblogs.com/feigao/p/9647238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值