.net模拟http请求

本文介绍了一种在项目中处理HTTP请求的方法,包括GET和POST请求的具体实现,通过使用C#语言,展示了如何发送请求并接收响应,适用于需要与外部API交互的场景。

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

在项目中会碰到需要调用网址get或者post数据的情况,下面就贴下我常用的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using LitJson;

namespace Common
{
    public class THttp
    {
        public static string GetHtml(string URL)
        {
            try
            {
                WebRequest wrt;
                wrt = WebRequest.Create(URL);
                wrt.Credentials = CredentialCache.DefaultCredentials;
                WebResponse wrp;
                wrp = wrt.GetResponse();
                string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                wrt.GetResponse().Close();
                return reader;
            }
            catch (WebException ex)
            {
                throw ex;
            }
        }
        public static string PostData(string RequestPara, string Url)
        {
            WebRequest hr = HttpWebRequest.Create(Url);

            byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
            hr.ContentType = "application/x-www-form-urlencoded";
            hr.ContentLength = buf.Length;
            hr.Method = "POST";

            System.IO.Stream RequestStream = hr.GetRequestStream();
            RequestStream.Write(buf, 0, buf.Length);
            RequestStream.Close();

            System.Net.WebResponse response = hr.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string ReturnVal = reader.ReadToEnd();
            reader.Close();
            response.Close();

            return ReturnVal;
        }
        public static byte[] StreamToBytes(Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }
            return bytes.ToArray();
        }
    }
}

其中GetHtml方法为http  get请求

PostData 为post请求 参数格式如下 par=data&par=data

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值