C# Post Json数据

public string Post(string Url, string jsonParas)
    {
        string strURL = Url;

        //创建一个HTTP请求 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
        //Post请求方式 
        request.Method = "POST";
        //内容类型
        request.ContentType = "application/x-www-form-urlencoded";

        //设置参数,并进行URL编码 

        string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   

        byte[] payload;
        //将Json字符串转化为字节 
        payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
        //设置请求的ContentLength  
        request.ContentLength = payload.Length;
        //发送请求,获得请求流 

        Stream writer;
        try
        {
            writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
        }
        catch (Exception)
        {
            writer = null;
            Console.Write("连接服务器失败!");
        }
        //将请求参数写入流
        writer.Write(payload, 0, payload.Length);
        writer.Close();//关闭请求流

        String strValue = "";//strValue为http响应所返回的字符流
        HttpWebResponse response;
        try
        {
            //获得响应流
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException ex)
        {
            response = ex.Response as HttpWebResponse;
        }

        Stream s = response.GetResponseStream();


        Stream postData = Request.InputStream;
        StreamReader sRead = new StreamReader(s);
        string postContent = sRead.ReadToEnd();
        sRead.Close();


        return postContent;//返回Json数据
    }


//接收
  //获取post过来的json数据结构
                    Stream postData = Request.InputStream;
                    StreamReader sRead = new StreamReader(postData);
                    string postContent = sRead.ReadToEnd();
                    sRead.Close();

posted @   太太怕我  阅读(24201)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示