C# 返回json 功能

发布于:2023-08-24 15:42:21

a0d7bfbbccbd32bf7305ed7a0d6e36a1.png

content = res.Result. Content 
string reslsgStr = res.Result.ToString();

JObject Jo = (JObject)JsonConvert,Deserialize0bject(resMsgStr);
string str = JsonConvert,Serialize0bject(res. Result);
string token = Jo[ Token ].ToString()



f29f32dfa66c15cc571c793e49520aa3.png




#region << 版 本 注 释 >>
/*----------------------------------------------------------------

 * 版本:V1.0.0
 * 描述:
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 时间:
 * 修改说明:
 *
 * 版本:V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;


namespace TDSoft.Apts.Utility
{
    /// <summary>
    /// HttpCall Http请求帮助类
    /// </summary>
    public class HttpCall
    {
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string data, string token = "")
        {
            string retString = string.Empty;
            try
            {
                string address = url;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);

                request.Method = "POST";
                request.ContentType = "application/json";
                //携带token
                if (!string.IsNullOrWhiteSpace(token))
                {
                    request.Headers.Add("Authorization", $"Bearer {token}");
                }
                string strContent = data; //json字符串
                using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
                {
                    dataStream.Write(strContent);
                    dataStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码  
                }
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                retString = reader.ReadToEnd();
            }
            catch (Exception ex)
            {

            }

            //解析josn
            //JObject jo = JObject.Parse(retString);
            return retString;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string token = "")
        {
            string content = string.Empty;
            try
            {
                //预备请求的资源
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                StreamReader reader = null;
                //实例化一个http请求
                request = (HttpWebRequest)WebRequest.Create(url);
                //设置请求头 请求方式method=get
                request.Method = "GET";
                //携带token
                if (!string.IsNullOrWhiteSpace(token))
                {
                    request.Headers.Add("Authorization", $"Bearer {token}");
                }
                //使request。getResponse()返回的一个响应对象
                response = (HttpWebResponse)request.GetResponse();
                //reader 读取响应流
                using (reader = new StreamReader(response.GetResponseStream()))
                {
                    //意思是从头读到尾,全部读完
                    content = reader.ReadToEnd();
                }

            }
            catch (Exception ex)
            {

            }

            return content;
        }


        #region from-data请求方式

        /// <summary>
        /// from-data请求方式
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static string HttpFromDataPost(string url, string jsonStr)
        {
            string content = "";
            try
            {
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = WebRequestMethods.Http.Post;
                request.KeepAlive = true;
                request.Timeout = -1;

                //认证方式
                //CredentialCache credentialCache = new CredentialCache();
                //credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("member", "secret"));
                //request.Credentials = credentialCache;

                request.ServicePoint.Expect100Continue = false;
                Dictionary<string, string> map = JsonStringToKeyValuePairs(jsonStr);
                using (Stream stream = request.GetRequestStream())
                {
                    //1.1 key/value
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    if (map != null)
                    {
                        foreach (string key in map.Keys)
                        {
                            stream.Write(boundarybytes, 0, boundarybytes.Length);
                            string formitem = string.Format(formdataTemplate, key, map[key]);
                            byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
                            stream.Write(formitembytes, 0, formitembytes.Length);
                        }
                    }
                    stream.Write(endbytes, 0, endbytes.Length);
                }
                //2.WebResponse
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (Stream responsestream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(responsestream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                content = ex.Message;
            }
            return content;
        }
        public static Dictionary<string, string> JsonStringToKeyValuePairs(string jsonStr)
        {
            char jsonBeginToken = '{';
            char jsonEndToken = '}';

            if (string.IsNullOrEmpty(jsonStr))
            {
                return null;
            }
            //验证json字符串格式
            if (jsonStr[0] != jsonBeginToken || jsonStr[jsonStr.Length - 1] != jsonEndToken)
            {
                throw new ArgumentException("非法的Json字符串!");
            }

            var resultDic = new Dictionary<string, string>();
            var jobj = JObject.Parse(jsonStr);
            JsonOn(jobj, resultDic);
            return resultDic;
        }
        private static Dictionary<string, string> JsonOn(JToken jobT, Dictionary<string, string> Dic)
        {

            //找出包含嵌套的字段列
            if (jobT is JObject jobj && jobj.Properties().Count() > 0)
            {
                foreach (var item in jobj.Properties())
                {
                    JsonProperties(item, Dic);
                }
            }
            else
            {
                Dic.Add(jobT.Path, jobT.ToString());

                return Dic;
            }
            return Dic;
        }
        private static Dictionary<string, string> JsonProperties(JProperty jobj, Dictionary<string, string> Dic)
        {
            return JsonOn(jobj.Value, Dic);
        }
        #endregion
    }

}




阅读 216+

一片空白

父爱如山,不善表达。回想十多年前,总记得父亲有个宽厚的肩膀,小小的自己跨坐在上面,越过人山人海去看更广阔的天空,那个时候期望自己有一双翅膀,能够像鸟儿一样飞得高,看得远。虽然父亲有时会和自己开玩笑,但在做错事的时候会受到严厉的训斥。父亲有双粗糙的大手掌。