关于接收json以及使用json

Common:

FileIO.cs

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace SMS.Util
{
    #region FileIo
    public class FileIO
    {

        private FileStream fsw;
        private StreamWriter sw;
        private string Charset = "UTF-8";

        public FileIO()
        {
        }

        public FileIO(string charset)
        {
            Charset = charset;
        }

        private void CreateDir(string filePath)
        {
            string dirPath = System.IO.Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
        }

        public void OpenWriteFile(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    CreateDir(filePath);
                    File.Create(filePath).Close();
                    fsw = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    sw = new StreamWriter(fsw, Encoding.GetEncoding(Charset));
                }
                else
                {
                    fsw = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    sw = new StreamWriter(fsw, Encoding.GetEncoding(Charset));
                }
            }
            catch
            {
            }
        }

        public void CloseWriteFile()
        {
            if (fsw != null)
            {
                fsw.Close();
            }
        }

        public void WriteLine(string s)
        {
            if (sw != null)
            {
                sw.WriteLine(s);
                sw.Flush();
            }
        }

        private FileStream fsr;
        private StreamReader sr;

        public void OpenReadFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                CreateDir(filePath);
                File.Create(filePath).Close();
            }
            fsr = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read,
            FileShare.ReadWrite);
            sr = new StreamReader(fsr, Encoding.GetEncoding(Charset));
        }

        public void CloseReadFile()
        {
            if (fsr != null)
                fsr.Close();
        }

        public string ReadLine()
        {
            if (sr.EndOfStream)
                return null;
            return sr.ReadLine();
        }

        public string ReadToEnd()
        {
            if (sr.EndOfStream) { return null; }
            return sr.ReadToEnd();
        }

        public bool IsEof()
        {
            return sr.EndOfStream;
        }
    }//ClassEnd
    #endregion
}

FileItem.cs

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;

namespace SMS.Util
{
    /// <summary>
    /// 文件元数据。
    /// 可以使用以下几种构造方法:
    /// 本地路径:new FileItem("C:/temp.jpg");
    /// 本地文件:new FileItem(new FileInfo("C:/temp.jpg"));
    /// 字节流:new FileItem("abc.jpg", bytes);
    /// </summary>
    public class FileItem
    {
        private string fileName;
        private string mimeType;
        private byte[] content;
        private FileInfo fileInfo;

        /// <summary>
        /// 基于本地文件的构造器。
        /// </summary>
        /// <param name="fileInfo">本地文件</param>
        public FileItem(FileInfo fileInfo)
        {
            if (fileInfo == null || !fileInfo.Exists)
            {
                throw new ArgumentException("fileInfo is null or not exists!");
            }
            this.fileInfo = fileInfo;
        }

        /// <summary>
        /// 基于本地文件全路径的构造器。
        /// </summary>
        /// <param name="filePath">本地文件全路径</param>
        public FileItem(string filePath)
            : this(new FileInfo(filePath))
        { }

        /// <summary>
        /// 基于文件名和字节流的构造器。
        /// </summary>
        /// <param name="fileName">文件名称(服务端持久化字节流到磁盘时的文件名)</param>
        /// <param name="content">文件字节流</param>
        public FileItem(string fileName, byte[] content)
        {
            if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");
            if (content == null || content.Length == 0) throw new ArgumentNullException("content");

            this.fileName = fileName;
            this.content = content;
        }

        /// <summary>
        /// 基于文件名、字节流和媒体类型的构造器。
        /// </summary>
        /// <param name="fileName">文件名(服务端持久化字节流到磁盘时的文件名)</param>
        /// <param name="content">文件字节流</param>
        /// <param name="mimeType">媒体类型</param>
        public FileItem(string fileName, byte[] content, string mimeType)
            : this(fileName, content)
        {
            if (string.IsNullOrEmpty(mimeType)) throw new ArgumentNullException("mimeType");
            this.mimeType = mimeType;
        }

        public string GetFileName()
        {
            if (this.fileName == null && this.fileInfo != null && this.fileInfo.Exists)
            {
                this.fileName = this.fileInfo.FullName;
            }
            return this.fileName;
        }

        public string GetMimeType()
        {
            if (this.mimeType == null)
            {
                this.mimeType = GetMimeType(GetContent());
            }
            return this.mimeType;
        }

        /// <summary>
        /// 获取文件的真实后缀名。目前只支持JPG, GIF, PNG, BMP四种图片文件。
        /// </summary>
        /// <param name="fileData">文件字节流</param>
        /// <returns>JPG, GIF, PNG or null</returns>
        public static string GetFileSuffix(byte[] fileData)
        {
            if (fileData == null || fileData.Length < 10)
            {
                return null;
            }

            if (fileData[0] == ‘G‘ && fileData[1] == ‘I‘ && fileData[2] == ‘F‘)
            {
                return "GIF";
            }
            else if (fileData[1] == ‘P‘ && fileData[2] == ‘N‘ && fileData[3] == ‘G‘)
            {
                return "PNG";
            }
            else if (fileData[6] == ‘J‘ && fileData[7] == ‘F‘ && fileData[8] == ‘I‘ && fileData[9] == ‘F‘)
            {
                return "JPG";
            }
            else if (fileData[0] == ‘B‘ && fileData[1] == ‘M‘)
            {
                return "BMP";
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取文件的真实媒体类型。目前只支持JPG, GIF, PNG, BMP四种图片文件。
        /// </summary>
        /// <param name="fileData">文件字节流</param>
        /// <returns>媒体类型</returns>
        public static string GetMimeType(byte[] fileData)
        {
            string suffix = GetFileSuffix(fileData);
            string mimeType;

            switch (suffix)
            {
                case "JPG": mimeType = "image/jpeg"; break;
                case "GIF": mimeType = "image/gif"; break;
                case "PNG": mimeType = "image/png"; break;
                case "BMP": mimeType = "image/bmp"; break;
                default: mimeType = "application/octet-stream"; break;
            }

            return mimeType;
        }

        /// <summary>
        /// 根据文件后缀名获取文件的媒体类型。
        /// </summary>
        /// <param name="fileName">带后缀的文件名或文件全名</param>
        /// <returns>媒体类型</returns>
        public static string GetMimeType(string fileName)
        {
            string mimeType;
            fileName = fileName.ToLower();

            if (fileName.EndsWith(".bmp", StringComparison.CurrentCulture))
            {
                mimeType = "image/bmp";
            }
            else if (fileName.EndsWith(".gif", StringComparison.CurrentCulture))
            {
                mimeType = "image/gif";
            }
            else if (fileName.EndsWith(".jpg", StringComparison.CurrentCulture) || fileName.EndsWith(".jpeg", StringComparison.CurrentCulture))
            {
                mimeType = "image/jpeg";
            }
            else if (fileName.EndsWith(".png", StringComparison.CurrentCulture))
            {
                mimeType = "image/png";
            }
            else
            {
                mimeType = "application/octet-stream";
            }

            return mimeType;
        }

        public byte[] GetContent()
        {
            if (this.content == null && this.fileInfo != null && this.fileInfo.Exists)
            {
                using (System.IO.Stream fileStream = this.fileInfo.OpenRead())
                {
                    this.content = new byte[fileStream.Length];
                    fileStream.Read(content, 0, content.Length);
                }
            }

            return this.content;
        }
    }
}

Logger.cs

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;

namespace SMS.Util
{
    public class Logger
    {
        #region 写文本日志

        /// <summary>
        /// 写文本日志
        /// </summary>
        /// <param name="Content"></param>
        /// <param name="logFilePath"></param>
        public static void WriteTxtLog(string Content, string logFilePath)
        {
            try
            {
                string fileName = logFilePath;
                string br = "\r\n";
                string content = Content;
                FileIO fIO = new FileIO();
                fIO.OpenWriteFile(fileName);
                fIO.WriteLine(content + br + br + "*******************************************************" + br);
                fIO.CloseWriteFile();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 写文本日志
        /// </summary>
        /// <param name="Content"></param>
        public static void WriteTxtLog(string Content)
        {
            try
            {
                string fileName = System.AppDomain.CurrentDomain.BaseDirectory;
                if (!fileName.EndsWith("\\"))
                {
                    fileName += "\\";
                }
                fileName += "Log\\";
                fileName += System.DateTime.Now.ToString("yyyy-MM-dd-HH") + ".txt";
                string br = "\r\n";
                string content = Content;
                FileIO fIO = new FileIO();
                fIO.OpenWriteFile(fileName);
                fIO.WriteLine(content + br + br + "*******************************************************" + br);
                fIO.CloseWriteFile();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 写文本日志
        /// </summary>
        /// <param name="Ex"></param>
        public static void WriteTxtLog(Exception Ex)
        {
            try
            {
                string fileName = System.AppDomain.CurrentDomain.BaseDirectory;
                if (!fileName.EndsWith("\\"))
                {
                    fileName += "\\";
                }
                fileName += "Log\\";
                fileName += System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                string blank = "    ";
                string br = "\r\n";
                string content = string.Empty;
                //content += "客户端IP:" + ClientIP;
                //content += br + "客户端操作系统:" + ClientPlatform;
                //content += br + "客户端浏览器:" + ClientBrowser;
                //content += br + "服务器计算机名:" + System.Net.Dns.GetHostName();
                //content += br + "发生时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //content += br + "引发页面:" + System.Web.HttpContext.Current.Request.Url.ToString();
                //content += br + "异常对象:" + Ex.Source;
                //content += br + "异常信息:" + Ex.Message;
                //content += br + "异常方法:" + Ex.TargetSite;
                //content += br + "错误详细信息:";
                content += br + blank + Ex.ToString();
                FileIO fIO = new FileIO();
                fIO.OpenWriteFile(fileName);
                fIO.WriteLine(content + br + br + "*******************************************************" + br);
                fIO.CloseWriteFile();
            }
            catch
            {
            }
        }
        #endregion

        #region 客户端IP
        /// <summary>
        /// 客户端IP
        /// </summary>
        private static string ClientIP
        {
            get
            {
                string result = String.Empty;
                result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                {
                    result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (null == result || result == String.Empty)
                {
                    result = System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                if (null == result || result == String.Empty)
                {
                    return "0.0.0.0";
                }
                return result;
            }
        }
        #endregion

        #region 客户端使用平台的名字
        /// <summary>
        /// 客户端使用平台的名字
        /// </summary>
        private static string ClientPlatform
        {
            get
            {
                try
                {
                    return System.Web.HttpContext.Current.Request.Browser.Platform.ToString();
                }
                catch { }
                {
                    return "";
                }
            }
        }
        #endregion

        #region 客户端浏览器
        /// <summary>
        /// 客户端浏览器
        /// </summary>
        private static string ClientBrowser
        {
            get
            {
                try
                {
                    System.Web.HttpBrowserCapabilities bc = System.Web.HttpContext.Current.Request.Browser;
                    return bc.Browser + " v." + bc.Version;
                }
                catch
                {
                    return "";
                }
            }
        }
        #endregion
    }//ClassEnd
}

Tools.cs

/*
 * 微信公众平台C#版SDK
 * www.qq8384.com 版权所有
 * 有任何疑问,请到官方网站:www.qq8484.com查看帮助文档
 * 您也可以联系QQ1397868397咨询
 * QQ群:124987242、191726276、234683801、273640175、234684104
*/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
//using System.Web.Script.Serialization;
using System.Xml;

namespace Weixin.Mp.Sdk.Util
{
    /// <summary>
    /// 辅助工具类
    /// </summary>
    public  class Tools
    {
        #region 获取Json string某节点的值。
        /// <summary>
        /// 获取Json string某节点的值。
        /// </summary>
        /// <param name="json"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetJosnValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim(‘"‘) + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号,若是最后一个,截“}”号,取最小值

                    int end = jsonStr.IndexOf(‘,‘, index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf(‘}‘, index);
                    }
                    //index = json.IndexOf(‘"‘, index + key.Length + 1) + 1;
                    result = jsonStr.Substring(index, end - index);
                    //过滤引号或空格
                    result = result.Trim(new char[] { ‘"‘, ‘ ‘, ‘\‘‘ });
                }
            }
            return result;
        }
        #endregion

        /// <summary>
        /// datetime转换成unixtime
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static  long  ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (long )(time - startTime).TotalSeconds;
        }

       /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
       /// </summary>
       /// <param name="d"></param>
       /// <returns></returns>
        public static System.DateTime ConvertIntDateTime(double d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddSeconds(d);
            return time;
        }

        /// <summary>
        /// Json序列化对象
        /// </summary>
        /// <typeparam name="ObjType"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        //public static  string ToJsonString<ObjType>(ObjType obj) where ObjType : class
        //{
        //    //JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        //    //string  s = jsonSerializer.Serialize(obj);
        //    //return s;
        //}

        //操作xml
       // public

    }
}

WebUtils.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace SMS.Util
{
    /// <summary>
    /// 网络工具类。
    /// </summary>
    public sealed class WebUtils
    {
        private int _timeout = 100000;

        /// <summary>
        /// 请求与响应的超时时间
        /// </summary>
        public int Timeout
        {
            get { return this._timeout; }
            set { this._timeout = value; }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">post数据</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, string postData)
        {
            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] bytePostData = Encoding.UTF8.GetBytes(postData);
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(bytePostData, 0, bytePostData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrEmpty(rsp.CharacterSet))
            {
                return GetResponseAsString(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, IDictionary<string, string> parameters)
        {
            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            if (string.IsNullOrEmpty(rsp.CharacterSet))
            {
                return GetResponseAsString(rsp, Encoding.UTF8);
            }
            else
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoGet(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }
           // writeBin("-------------------------第二次读取url:" + url);
            HttpWebRequest req = GetWebRequest(url, "GET");
          //  writeBin("-------------------------11"+req);
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
//
          //  writeBin("-------------------------22" + req);
            if (req != null)
            {
              //  writeBin("--------------------req不为空---------------");
                //writeBin(req.ToString());
            }
            else
            {
               // writeBin("------------------req为空了-------");
               // writeBin(req.ToString());
            }
            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //writeBin("-------------------------33");
            if (string.IsNullOrEmpty(rsp.CharacterSet))
            {
                //writeBin("-------------------------repSet为空:"+rsp);
                return GetResponseAsString(rsp, Encoding.UTF8);
            }
            else
            {
                //writeBin("-------------------------repSetNo空:"+rsp.CharacterSet);
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        public void writeBin(string texts)
        {
            //获取路径
            string LoginPath = AppDomain.CurrentDomain.BaseDirectory + "\\AsyncMemberinfo.bin";
            //服务器一切正常
            FileStream fs = new FileStream(LoginPath, FileMode.Append);
            StringBuilder sbu = new StringBuilder();
            sbu.AppendLine(texts);
            BinaryWriter bwrite = new BinaryWriter(fs, System.Text.Encoding.Default);
            bwrite.Write(sbu.ToString());
            bwrite.Flush();
            fs.Close();
        }

        /// <summary>
        /// 执行带文件上传的HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="fileParams">请求文件参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams)
        {
            // 如果没有文件参数,则走普通POST请求
            if (fileParams == null || fileParams.Count == 0)
            {
                return DoPost(url, textParams);
            }

            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;

            System.IO.Stream reqStream = req.GetRequestStream();
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            // 组装文本请求参数
            string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
            IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
            while (textEnum.MoveNext())
            {
                string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                byte[] itemBytes = Encoding.UTF8.GetBytes(textEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);
            }

            // 组装文件请求参数
            string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
            IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
            while (fileEnum.MoveNext())
            {
                string key = fileEnum.Current.Key;
                FileItem fileItem = fileEnum.Current.Value;
                string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
                byte[] itemBytes = Encoding.UTF8.GetBytes(fileEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);

                byte[] fileBytes = fileItem.GetContent();
                reqStream.Write(fileBytes, 0, fileBytes.Length);
            }

            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        { //直接确认,否则打不开
            //writeBin("进入内部服务器");
         //   writeBin("内部分析器:" + sender + "X509Certificate:" + certificate + "X509Chain:" + chain + "SslPolicyErrors:" + errors);
            return true;
        }

        public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = null;
            if (url.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                req = (HttpWebRequest)WebRequest.Create(url);
            }

            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "WeixinMpSdk";
            req.Timeout = this._timeout;

            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 组装GET请求URL。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>带参数的GET请求URL</returns>
        public string BuildGetUrl(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }
            return url;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }

        private static bool  DownloadQrCode(string url, string saveDir, out string saveFileName, out string errHtml)
        {
            Stream outStream = null;
            WebClient wc = null;
            errHtml = string.Empty;
            if (!saveDir.EndsWith("\\"))
            {
                saveDir += "\\";
            }
            saveFileName = saveDir + System.Guid.NewGuid().ToString() + ".jpg";
            try
            {

                wc = new WebClient();
                var data = wc.DownloadData(url);

                if (File.Exists(saveFileName))
                    File.Delete(saveFileName);
                outStream = System.IO.File.Create(saveFileName);

                foreach (var b in data)
                {
                    outStream.WriteByte(b);
                }
                return true;
            }
            catch (Exception ex)
            {
                errHtml = ex.Message;
                return false;
            }
            finally
            {
                if (wc != null)
                {
                    wc.Dispose();
                }
                if (outStream != null)
                {
                    outStream.Close();
                }
            }
        }

        public bool DownloadFile(string url, string saveDir, out string saveFileName,out string errHtml)
        {
            if (url.IndexOf("showqrcode") != -1)
            {
                return DownloadQrCode(url, saveDir, out  saveFileName, out  errHtml);
            }

            saveFileName = string.Empty;
            errHtml = string.Empty;
            bool isSuc = false;
            HttpWebResponse  response = null;
            HttpWebRequest request = null;

            try
            {

                request = GetWebRequest(url, "GET");
               // if (url.IndexOf("showqrcode") != -1)
                //{
                //    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0";
                //}

                response = (HttpWebResponse)request.GetResponse();
                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    string disp = response.Headers.Get("Content-disposition");
                    string ext = disp.Substring(disp.LastIndexOf("."));
                    ext = ext.Substring(0, ext.Length - 1);
                    saveFileName = saveDir;
                    if (!saveFileName.EndsWith("\\"))
                    {
                        saveFileName += "\\";
                    }
                    saveFileName = saveFileName + System.Guid.NewGuid().ToString() + ext;
                    SaveBinaryFile(response, saveFileName);
                    isSuc = true;
                }
                else
                {
                    if (string.IsNullOrEmpty(response.CharacterSet))
                    {
                        errHtml = GetResponseAsString(response, Encoding.UTF8);
                    }
                    else
                    {
                        Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
                        errHtml = GetResponseAsString(response, encoding);
                    }
                    isSuc = false;
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request = null;
                }
            }

            return isSuc;
        }

        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }

    } //class end
}

JsonTest.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;

namespace WebTest.Common
{
    public class JsonTest<T> where T:new()
    {
        public static T jsonToOrder(string jsons)
        {
            T t = JsonConvert.DeserializeObject<T>(jsons);
            return t;
        }
    }
}

TestDemo1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestDemo1.aspx.cs" Inherits="WebTest.TestDemo1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="userToken" type="text" runat="server" />
       <%-- <input id="submitOK" type="button" onclick="return subAsync();">--%>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">

    function subAsync() {
        var userMes = $("#userToken").val();

        $.ajax({
            url: "http://member.joycp.com/ajax/takemoney.ashx?requestType=1&j_token=" + userMes,
            type: "get",
            async: false,
            dataType:"jsonp",
            success: function (data) {
                if (data != "") {
                    alert(data);
                } else {
                    alert("数据为空了");
                }
            },
            error: function () {
                alert("出错了!");
            }
        });
    }

</script>

TestDemo1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebTest.Common;

namespace WebTest
{
    public partial class TestDemo1 : System.Web.UI.Page
    {
        private string myTooken = "";
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            myTooken += this.userToken.Value;
            SMS.Util.WebUtils uti = new SMS.Util.WebUtils();
            string s = uti.DoGet(myTooken, null);
            newModel mode =  JsonTest<newModel>.jsonToOrder(s);
            Response.Write("状态:" + mode.Stat + "||消息:" + mode.Msg + "||时间:" + mode.Data);
        }

    }
    public class newModel
    {
        public int Stat { get; set; }
        public string Msg { get; set; }
        public string Data { get; set; }
    }

}
时间: 2024-10-01 12:51:28

关于接收json以及使用json的相关文章

Spring 接收转换 jquery ajax json数组字符串

1.ajax发送json字符串 </pre><p>组建对象</p><p></p><pre code_snippet_id="449843" snippet_file_name="blog_20140813_2_7927326" name="code" class="javascript">var student = new Object(); studen

spring mvc 处理接收的map 转换为 json 格式

开发中会遇到传递的map 参数以json 格式处理 ,springMVC中配置如下代码即可实现 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- JSON解析对象 --> <bean

spring mvc接收ajax提交的JSON数据,并反序列化为对象

需求:spring mvc接收ajax提交的JSON数据,并反序列化为对象,代码如下: 前台JS代码: //属性要与带转化的对象属性对应 var param={name:'语文',price:16}; $.ajax({ url: "/book/adddata", type: "POST", dataType: 'json', //必需设定,后台@RequestBody会根据它做数据反序列化 contentType:"application/json&quo

struts2 接口如何接收客户端提交的json数据

struts2 接口如何接收客户端提交的json数据 CreationTime--2018年6月20日15点54分 Author:Marydon 1.情景还原 使用struts2写的接口(服务端),要求对方(客户端)以json格式传输数据,但是使用request.getParameter()获取不到 2.问题剖析 application/x- www-form-urlencoded是Post请求默认的请求体内容类型,也是form表单默认的类型,可以使用request.getParameter()

将php数组转js数组,js如何接收PHP数组,json的用法

首先下载下面这个文件(这是一段是别人写出来专门解析json的代码),然后引入这个文件! http://pan.baidu.com/s/1dD8qVr7 现在当我们需要用ajax与后台进行交互时,怎样将php的数组传送到js文件并且并js所识别? 先看php文件,当我们获取到$arr这个数组后 foreach ($arr as $value) { $json .= json_encode($value) . ','; } echo '[' . substr($json,0,strlen($json

json.stringfy()和json.parse()

json.stringfy()将对象.数组转换成json:json.parse()将json转成对象. json.stringfy(): 语法:  JSON.stringify(value [, replacer] [, space]) value:是必选字段.就是你输入的对象,比如数组,类等. replacer:这个是可选的.它又分为2种方式,一种是数组,第二种是方法. 情况一:replacer为数组时,通过后面的实验可以知道,它是和第一个参数value有关系的.一般来说,系列化后的结果是通过

WCF JSON DATETIME JSON.NET (Newtonsoft.Json.dll)

[DataMember] public DateTime? myTime { get; set; } var timeFormat = new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }; string json = JsonConvert.SerializeObject(send, timeFormat); ResultData rd = JsonConvert

有关javascript中的JSON.parse和JSON.stringify的使用一二

有没有想过,当我们的大后台只是扮演一个数据库的角色,json在前后台的数据交换中扮演极其重要的角色时,作为依托node的前端开发,其实相当多的时间都是在处理数据,准确地说就是在处理逻辑和数据(这周实习最大的收获). 而对于依托json格式传输的数据,处理数据时,用到JSON.strinify和JSON.parse的概率是百分之百.使用这两个方法so easy,但是你真的知道其中一些相关的细节以及其中牵涉到的javascript的知识么? JSON.parse用于从一个字符串中解析出json对象.

【荐】使用eval()、new Function()将JSON字符串转换为JSON对象

在JS中将JSON的字符串解析成JSON数据格式,一般有两种方式: 1.一种为使用eval()函数. 2. 使用Function对象来进行返回解析. 第一种解析方式:使用eval函数来解析,并且使用jQuery的each方法来遍历 用jQuery解析JSON数据的方法,作为jQuery异步请求的传输对象,jQuery请求后返回的结果是json对象,这里考虑的都是服务器返回JSON形式的字符串的形式,对于利用JSONObject等插件封装的JSON对象,与此亦是大同小异,这里不再做说明. 这里首先

JSON对象和JSON字符串

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JSON.parse()</titl