C# 使用Http Post方式发送Json数据,只需二步。

一.先在工程增加 RestClient.cs类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CM2.CentreWin
{
class RestClient
{
private System.Net.CookieContainer Cookies = new System.Net.CookieContainer();
private string BaseUri;
public RestClient(string baseUri)
{
this.BaseUri = baseUri;
}

    #region Get请求
    public string Get(string uri)
    {
        //先根据用户请求的uri构造请求地址
        string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
        //创建Web访问对  象
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
        //通过Web访问对象获取响应内容
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
        string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
        reader.Close();
        myResponse.Close();
        return returnXml;
    }

    //internal string Post(string v)
    //{
    //    throw new NotImplementedException();
    //}
    #endregion

    #region Post请求
    public string Post(string data, string uri)
    {

#if true

        //先根据用户请求的uri构造请求地址
        string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
        //创建Web访问对象
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);


        //myRequest.ServicePoint.Expect100Continue = false; // 取消100-continue

        //private System.Net.CookieContainer Cookies = new System.Net.CookieContainer();
        //myRequest.CookieContainer = Cookies; //头后面加两个 \r\n

        //ServicePointManager.Expect100Continue = false;// 取消100-continue
        //ServicePointManager.UseNagleAlgorithm = true;
        //ServicePointManager.Expect100Continue = true;
        //ServicePointManager.CheckCertificateRevocationList = true;
        //ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;


       
        //myRequest.ServicePoint.ConnectionLimit = 3000;

        //myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11";

        //把用户传过来的数据转成“UTF-8”的字节流
        byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);




        myRequest.Method = "POST";
        myRequest.ContentType = "application/json";//Http内容类型
        myRequest.MaximumAutomaticRedirections = 1;//获取或设置请求将跟随的重定向的最大数目。
        myRequest.AllowAutoRedirect = true;//获取或设置一个值,该值指示请求是否应跟随重定向响应。
        myRequest.SendChunked = false;//获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
        myRequest.CookieContainer = Cookies;//获取或设置与此请求关联的cookie。
        myRequest.UserAgent = "cps";//获取或设置 User-agent HTTP 标头的值
        myRequest.Timeout = 18000;//获取或设置请求的超时值。 设置请求超时时间,单位为毫秒

        myRequest.ContentLength = buf.Length;




        //发送请求
        //Stream stream = myRequest.GetRequestStream();
       Stream stream = null;

      

        try
        {
            stream = myRequest.GetRequestStream();  //获取用于写入请求数据的Stream对象
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
             return "";
         }

        
        stream.Write(buf, 0, buf.Length);
        stream.Close();




        //获取接口返回值
        //通过Web访问对象获取响应内容
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
        string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
        reader.Close();
        myResponse.Close();



        return returnXml;

#endif

    }
    #endregion




    #region Put请求
    public string Put(string data, string uri)
    {
        //先根据用户请求的uri构造请求地址
        string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
        //创建Web访问对象
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
        //把用户传过来的数据转成“UTF-8”的字节流
        byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

        myRequest.Method = "PUT";
        myRequest.ContentLength = buf.Length;
        myRequest.ContentType = "application/json";
        myRequest.MaximumAutomaticRedirections = 1;
        myRequest.AllowAutoRedirect = true;
        //发送请求
        Stream stream = myRequest.GetRequestStream();
        stream.Write(buf, 0, buf.Length);
        stream.Close();

        //获取接口返回值
        //通过Web访问对象获取响应内容
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
        string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
        reader.Close();
        myResponse.Close();
        return returnXml;

    }

#endregion

#region Delete请求
public string Delete(string data, string uri)
{
//先根据用户请求的uri构造请求地址
string serviceUrl = string.Format(“{0}/{1}”, this.BaseUri, uri);
//创建Web访问对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//把用户传过来的数据转成“UTF-8”的字节流
byte[] buf = System.Text.Encoding.GetEncoding(“UTF-8”).GetBytes(data);

        myRequest.Method = "DELETE";
        myRequest.ContentLength = buf.Length;
        myRequest.ContentType = "application/json";
        myRequest.MaximumAutomaticRedirections = 1;
        myRequest.AllowAutoRedirect = true;
        //发送请求
        Stream stream = myRequest.GetRequestStream();
        stream.Write(buf, 0, buf.Length);
        stream.Close();

        //获取接口返回值
        //通过Web访问对象获取响应内容
        HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
        //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
        //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
        string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
        reader.Close();
        myResponse.Close();
        return returnXml;

    }

#endregion

}

}

二.调用Post发送数据

            RestClient client = new RestClient("http://192.168.001.110:8086");
            string result = client.Post("{"day":8,"hour":15,"min":42,"month":5,"sec":15,"week":1,"year":2023}", "api/v1/settimecfg");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZCY5202015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值