C# 做post上发数据Api

C# 做post上发数据Api

猿掌柜
2021-10-24 / 1 评论 / 21 阅读 / 正在检测是否收录...

接口函数

public string Post(string url, string stringJson)
        {
            try
            {
                string result = "";
                string user = "admin";
                string pwd = "123456";
                string auth = user+":"+pwd;
                //string timestampnow = ConvertDateTimeLong(DateTime.Now).ToString();
                string methods = "POST";
                string signature = "c2hpbmVlbmVyZ3k6U2hpbmVlbmVyZ3kxMjM0NTY3YQ==";//Authorization: “username:password”通过base64加密后的字符串
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Headers.Add("authorization", signature);
                req.Method = methods;
                req.ContentType = "application/json";
                #region 添加Post 参数
                byte[] data = Encoding.UTF8.GetBytes(stringJson);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                //Console.WriteLine(result);
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString() + " " + ex.Message);
                return null;
            }
        }

直接调用即可
参数url json 字符串

0

评论 (1)

取消
  1. 头像
    assd
    Ubuntu · FireFox

    学习了

    回复