C# Http

1.C# application/x-www-from-urlencoded 请求类型  == PostMan x-www-from-urlencoded 类型

        /// <summary>
        /// 公共请求方法
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="body">body</param>
        /// <returns></returns>
        public static string MesPostApi(string url,string body)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-from-urlencoded";
            request.AllowAutoRedirect = true;
            request.Timeout = 20 * 1000;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("x-cherun-auth-key", "LarxMbndsxfGwoYAqsfJSPPU42l04cb3");
            byte[] byteArray = Encoding.Default.GetBytes(body);
            request.ContentLength = byteArray.Length;
            using (Stream newStream = request.GetRequestStream())
            {
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
            }

            string EndResult = string.Empty;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream rspStream = response.GetResponseStream();
            using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
            {
                EndResult = reader.ReadToEnd();
                rspStream.Close();
            }
            response.Close();

            return EndResult;
        }    
/*
* 请求参数的组装格式 列
*  beginData=xxx&endDate=xxx&pageNumber=xxx&pageSize=xxx
*/


//组装请求参数
        public static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            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))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString(); 
        }

application/x-www-from-urlencoded  这种HTTP请求 注意的一点就是参数的组装格式,不是我们常用的 json格式的!

这种格式是无法传文件或图片的,想要通过http请求或发送文件、图片。要使用另外的一种请求格式:Content-Type: multipart/form-data;

直接看代码:值拼接示例:(postMan 截图)

C# Http

项目代码:

 /// <summary>
    /// 表单提交
    /// </summary>
    public class MesApiPostFormData
    {
        /// <summary>
        /// 表单键,request["key"]
        /// </summary>
        public string Key { set; get; }
        /// <summary>
        /// 表单值,上传文件时忽略,request["key"].value
        /// </summary>
        public string Value { set; get; }
        /// <summary>
        /// 是否是文件
        /// </summary>
        public bool IsFile
        {
            get
            {
                if (FileContent == null || FileContent.Length == 0)
                    return false;

                if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))
                    throw new Exception("上传文件时 FileName 属性值不能为空");
                return true;
            }
        }
        /// <summary>
        /// 上传的文件名
        /// </summary>
        public string FileName { set; get; }
        /// <summary>
        /// 上传的文件内容
        /// </summary>
        public Stream FileContent { set; get; }
    }

  /// <summary>
        /// 
        /// </summary>
        /// <param name="app_key">key</param>
        /// <param name="method">方法名</param>
        /// <param name="body">body</param>
        /// <returns></returns>
        public static T MesPostApi<T>(string method, string body, string hander, string fileUrl = null)
        {
            //系统参数根据自己实际需要赋值
            string app_key = "test";
            string secret = "test";
            string access_token = "test";
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string v = "1.0";
            //sign  根据接口要求 进行拼接 加密
            string sign = GetMD5("xxxxxx");

            Dictionary<string, string> keys = new Dictionary<string, string>();
            keys.Add("app_key", app_key);
            keys.Add("access_token", access_token);
            keys.Add("timestamp", timestamp);
            keys.Add("method", method);
            keys.Add("v", "1.0");
            keys.Add("sign", sign);
            keys.Add("body", body);

            var formData = new List<MesApiPostFormData>();
            foreach (var kv in keys)
            {
                formData.Add(new MesApiPostFormData()
                {
                    Key = kv.Key,
                    Value = kv.Value
                });
            }

            if (!string.IsNullOrWhiteSpace(fileUrl))
            {
                Stream stream = ExcelOrImgToStream(fileUrl);
                string fileName = Path.GetFileName(fileUrl);
                formData.Add(new MesApiPostFormData()
                {
                    Key = "file",
                    FileName = fileName,
                    FileContent = stream
                });
            }
            string url = string.Format(mesUrl, hander);
            var result = JsonConvert.DeserializeObject<T>(ApiTool.PostForm(url, formData));
            return result;
        }

        /// <summary>
        /// 32位小写MD5值
        /// </summary>
        /// <returns></returns>
        private static string GetMD5(string myString)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = Encoding.UTF8.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++)
            {
                byte2String = byte2String + targetData[i].ToString("x2");
            }

            return byte2String;
        }

        /// <summary>
        /// 将图片或文档转为流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static Stream ExcelOrImgToStream(string url)
        {
            // 打开文件
            FileStream fileStream = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.Read);

            // 读取文件的 byte[]
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            // 把 byte[] 转换成 Stream
            Stream stream = new MemoryStream(bytes);
            return stream;
        }


        /// <summary>
        /// 使用Post方法获取字符串结果(借鉴过网上的写法)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formItems">Post表单内容</param>
        /// <param name="cookieContainer"></param>
        /// <param name="timeOut">默认20秒</param>
        /// <param name="encoding">响应内容的编码类型(默认utf-8)</param>
        /// <returns></returns>
        public static string PostForm(string url, List<MesApiPostFormData> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            #region 初始化请求对象
            request.Method = "POST";
            request.Timeout = timeOut;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            if (!string.IsNullOrEmpty(refererUrl))
                request.Referer = refererUrl;
            if (cookieContainer != null)
                request.CookieContainer = cookieContainer;
            #endregion

            string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //请求流
            var postStream = new MemoryStream();
            #region 处理Form表单请求内容
            //是否用Form上传文件
            var formUploadFile = formItems != null && formItems.Count > 0;
            if (formUploadFile)
            {
                //文件数据模板
                string fileFormdataTemplate =
                    "\r\n--" + boundary +
                    "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
                    "\r\nContent-Type: application/octet-stream" +
                    "\r\n\r\n";
                //文本数据模板
                string dataFormdataTemplate =
                    "\r\n--" + boundary +
                    "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                    "\r\n\r\n{1}";
                foreach (var item in formItems)
                {
                    string formdata = null;
                    if (item.IsFile)
                    {
                        //上传文件
                        formdata = string.Format(
                            fileFormdataTemplate,
                            item.Key, //表单键
                            item.FileName);
                    }
                    else
                    {
                        //上传文本
                        formdata = string.Format(
                            dataFormdataTemplate,
                            item.Key,
                            item.Value);
                    }

                    //统一处理
                    byte[] formdataBytes = null;
                    //第一行不需要换行
                    if (postStream.Length == 0)
                        formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
                    else
                        formdataBytes = Encoding.UTF8.GetBytes(formdata);
                    postStream.Write(formdataBytes, 0, formdataBytes.Length);

                    //写入文件内容
                    if (item.FileContent != null && item.FileContent.Length > 0)
                    {
                        using (var stream = item.FileContent)
                        {
                            byte[] buffer = new byte[1024];
                            int bytesRead = 0;
                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                postStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
                //结尾
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                postStream.Write(footer, 0, footer.Length);
            }
            else
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }
            #endregion

            request.ContentLength = postStream.Length;

            #region 输入二进制流
            if (postStream != null)
            {
                postStream.Position = 0;
                //直接写入流
                Stream requestStream = request.GetRequestStream();

                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                postStream.Close();//关闭文件访问
            }
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
                {
                    string retString = myStreamReader.ReadToEnd();
                    return retString;
                }
            }
        }        

 

C# Http

上一篇:C# 常见操作


下一篇:Netty核心组件Future与ChannelFuture