C# https post json格式调用接口

C#调用API接口进行数据交互的实现
该代码示例展示了如何使用C#通过Newtonsoft.Json库构造JSON请求,调用HTTPS API接口,并处理SSL证书验证。方法包括设置HTTP请求头,发送POST请求,接收并解析返回的JSON数据。
using Newtonsoft.Json.Linq;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.IO;
using System.Net;

 private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";
        // private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        //{
        //     return true; //总是接受   
        // }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        public static string Base64Encode(Encoding encodeType, string source)
        {
            string encode = string.Empty;
            byte[] bytes = encodeType.GetBytes(source);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = source;
            }
            return encode;
        }

  public static string PostToYS(string access_token, string account, string year, string ystype)
        {
            try
            {
                string returnjsonlist = "";
                var dataset = HLYSetCode.FindAll("", "", "", 0, 0);
                string url = System.Configuration.ConfigurationManager.AppSettings["HLYGetYSURL"];
                JObject patientinfo = new JObject();
                JObject patientinfolist = new JObject();
                JArray queryLineList1 = new JArray();
                JArray queryLineList2 = new JArray();
                JArray queryParameterList1 = new JArray();
                JArray queryParameterList2 = new JArray();
                JObject user = new JObject();
                JObject user1 = new JObject();
                JObject userB = new JObject();
                JObject userB1 = new JObject();
                user1["parameterValueCode"] = account + ystype;
                queryParameterList1.Add(user1);
                user["parameterType"] = "BGT_RULE_PARAMETER_BUDGET";
                user["parameterCode"] = "BUDGET_ITEM";
                //user["isAll"] = "false";
                //user["parameterType"] = dataset[0].ParameterType;
                //user["parameterCode"] = dataset[0].ParameterCode;
                user["isAll"] = dataset[0].IsAll;
                user["queryParameterList"] = queryParameterList1;
                queryLineList1.Add(user);

                userB1["parameterValueCode"] = ystype;
                queryParameterList2.Add(userB1);
                userB["parameterType"] = "BGT_RULE_PARAMETER_DIM";
                userB["parameterCode"] = "2";
                userB["isAll"] = "false";
                userB["queryParameterList"] = queryParameterList2;
                queryLineList1.Add(userB);
                //patientinfo["companyCode"] = "001";
                //patientinfo["organizationCode"] = "01";
                //patientinfo["scenarioCode"] = "1";
                //patientinfo["versionCode"] = "1";
                //patientinfo["structureCode"] = "777";
                //patientinfo["conditionCode"] = "001";
                //patientinfo["conditionName"] = "申万菱信控制策略";
                //patientinfo["periodSummaryFlag"] = true;
                //patientinfo["amountQuarterFlag"] = "AMOUNT";
                patientinfo["companyCode"] = dataset[0].CompanyCode;
                patientinfo["organizationCode"] = dataset[0].OrganizationCode;
                patientinfo["scenarioCode"] = dataset[0].ScenarioCode;
                patientinfo["versionCode"] = dataset[0].VersionCode;
                patientinfo["structureCode"] = dataset[0].StructureCode;
                patientinfo["conditionCode"] = dataset[0].ConditionCode;
                patientinfo["conditionName"] = dataset[0].ConditionName;
                patientinfo["periodSummaryFlag"] = dataset[0].PeriodSummaryFlag;
                patientinfo["amountQuarterFlag"] = dataset[0].AmountQuarterFlag;
                patientinfo["yearLimit"] = year;
                patientinfo["periodLowerLimit"] = year + "-01";
                patientinfo["periodUpperLimit"] = year + "-12";
                //patientinfo["versionNumber"] = 2;
                patientinfo["versionNumber"] = Convert.ToInt32(dataset[0].VersionNumber);
                patientinfo["queryLineList"] = queryLineList1;
                //上面拼接json格式参数
                string body = JsonConvert.SerializeObject(patientinfo);
                //eg:  发送Url需要的格式:sendData={"ids":[123],"Name":小黑}
                HttpWebRequest request = null;
                CookieContainer cookie = new CookieContainer();
                 ServicePointManager.Expect100Continue = false; //2022-12-05调接口时突然报500错误,加了这句就可以了。
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;//证书,.net framework4.5以上
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  
                 ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
 
                request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = cookie;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Method = "POST";
                request.ContentType = "application/json";
                request.UserAgent = DefaultUserAgent;
                request.KeepAlive = true;
                request.Headers["Authorization"] = "Bearer " + access_token;
                
                byte[] byteData = Encoding.UTF8.GetBytes(body);
                int length = byteData.Length;
                request.ContentLength = length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(byteData, 0, byteData.Length);
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (StreamReader st = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    returnjsonlist = st.ReadToEnd().ToString();
                    // return st.ReadToEnd().ToString();
                    JObject jo = (JObject)JsonConvert.DeserializeObject(returnjsonlist);
                    access_token = jo["message"].ToString();
                }
                return returnjsonlist;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
### 如何在 C# 中通过 HTTP/HTTPS 协议以 POST 方式发送 JSON 数据 要在 C# 中实现通过 HTTP/HTTPSPOST 请求来发送 JSON 数据,可以利用 `HttpClient` 类完成这一操作。以下是详细的说明以及示例代码。 #### 使用 HttpClient 进行 POST 请求并发送 JSON 数据 `HttpClient` 是 .NET 平台中用于发起 HTTP 请求的核心类之一。它支持多种类型的请求方法(GET、POST 等)。为了发送 JSON 数据,通常会将对象序列化为 JSON 字符串,并将其作为内容传递给服务器[^1]。 下面是一个完整的示例: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; public class Program { public static async Task Main(string[] args) { var client = new HttpClient(); client.BaseAddress = new Uri("https://example.com/api/"); // 创建要发送的数据模型 var dataModel = new DataModel { Name = "Test", Value = 42 }; // 将数据模型序列化为 JSON 字符串 string jsonContent = JsonConvert.SerializeObject(dataModel); // 创建 HttpContent 对象并将 JSON 字符串设置为其内容 var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); // 发起 POST 请求 HttpResponseMessage response = await client.PostAsync("endpoint", content); // 检查响应状态码 if (response.IsSuccessStatusCode) { Console.WriteLine("Request succeeded."); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response Body: {responseBody}"); } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); } client.Dispose(); } } // 定义数据模型 public class DataModel { public string Name { get; set; } public int Value { get; set; } } ``` 上述代码展示了如何创建一个简单的 POST 请求,并附带 JSON 数据。主要步骤如下: - 初始化 `HttpClient` 实例。 - 构建需要传输的对象实例,并使用 `JsonConvert.SerializeObject()` 方法将其转换为 JSON 格式的字符串[^3]。 - 利用 `StringContent` 设置 Content-Type 头部为 `"application/json"`,并通过其构造函数指定编码格式。 - 调用 `PostAsync` 方法执行实际的网络通信过程。 #### 关于 HTTPS 支持 当目标 URL 开头为 `https://` 时,默认情况下 `.NET Framework/.NET Core` 已经集成了 SSL/TLS 加密机制的支持,因此无需额外配置即可安全地向远程服务端提交敏感信息。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值