C#分析URL参数获取参数和值得对应列表(二)

C# winform post 请求指定 url

/// <summary>
    /// 请求信息帮助
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// post 请求指定地址返回响应数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="timeout">请求超时时间(毫秒)</param>
        /// <param name="requestCoding">请求编码</param>
        /// <param name="responseCoding">响应编码</param>
        /// <returns></returns>
        public string PostRequest(string url, Dictionary<string, string> postData, int timeout, Encoding requestCoding, Encoding responseCoding)
        {
            string postStr = string.Empty;
            if (postData != null)
            {
                postData.All(o =>
                               {
                                   if (string.IsNullOrEmpty(postStr))
                                       postStr = string.Format("{0}={1}", o.Key, o.Value);
                                   else
                                       postStr += string.Format("&{0}={1}", o.Key, o.Value);

                                   return true;
                               });
            }
            return PostRequest(url, postStr, timeout, requestCoding, responseCoding);
        }
        /// <summary>
        /// post 请求指定地址返回响应数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">请求数据</param>
        /// <param name="timeout">请求超时时间(毫秒)</param>
        /// <param name="requestCoding">请求编码</param>
        /// <param name="responseCoding">响应编码</param>
        /// <returns></returns>
        public string PostRequest(string url, string postData, int timeout, Encoding requestCoding, Encoding responseCoding)
        {
            string postUrl = VerifyUrl(url);
            try
            {
                //写入POSTDATE里
                byte[] byteArray = requestCoding.GetBytes(postData);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webRequest.Method = "POST";
                webRequest.Timeout = timeout;
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = byteArray.Length;
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                //接收返回信息:
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                StreamReader php = new StreamReader(response.GetResponseStream(), responseCoding);
                string result = php.ReadToEnd();
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 验证URL
        /// </summary>
        /// <param name="url">待验证 URL</param>
        /// <returns></returns>
        private string VerifyUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                throw new Exception("URL 地址不可以为空!");

            if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
                return url;

            return string.Format("http://{1}", url);
        }
    }
 /// <summary>
    /// Http请求
    /// </summary>
    public class HttpUtility
    {
        /// <summary>
        ///通用HttpWebRequest
        /// </summary>
        /// <param name="method">请求方式(POST/GET)</param>
        /// <param name="url">请求地址</param>
        /// <param name="param">请求参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public static string Request(string method, string url, string param, Action<HttpStatusCode, string> onComplete = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("URL");

            switch (method.ToUpper())
            {
                case "POST":
                    return Post(url, param, onComplete);
                case "GET":
                    return Get(url, param, onComplete);
                default:
                    throw new EntryPointNotFoundException("method:" + method);
            }
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回的结果</returns>
        public static string Post(string url, string param, Action<HttpStatusCode, string> onComplete = null)
        {
            UrlCheck(ref url);

            byte[] bufferBytes = Encoding.UTF8.GetBytes(param);

            var request = WebRequest.Create(url) as HttpWebRequest;//HttpWebRequest方法继承自WebRequest, Create方法在WebRequest中定义,因此此处要显示的转换
            request.Method = "POST";
            request.ContentLength = bufferBytes.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            try
            {
                using (var requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bufferBytes, 0, bufferBytes.Length);
                }
            }
            catch (WebException ex)
            {

                return ex.Message;
            }

            return HttpRequest(request, onComplete);
        }

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        public static string Get(string url, string param, Action<HttpStatusCode, string> onComplete = null)
        {
            UrlCheck(ref url);

            if (!string.IsNullOrEmpty(param))
                if (!param.StartsWith("?"))
                    param += "?" + param;
                else
                    param += param;

            var request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            return HttpRequest(request, onComplete);
        }

        /// <summary>
        /// 请求的主体部分(由此完成请求并返回请求结果)
        /// </summary>
        /// <param name="request">请求的对象</param>
        /// <param name="onComplete">完成后执行的操作(可选参数,通过此方法可以获取到HTTP状态码)</param>
        /// <returns>请求返回结果</returns>
        private static string HttpRequest(HttpWebRequest request, Action<HttpStatusCode, string> onComplete = null)
        {
            HttpWebResponse response = null;

            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            if (response == null)
            {
                if (onComplete != null)
                    onComplete(HttpStatusCode.NotFound, "请求远程返回为空");
                return null;
            }

            string result = string.Empty;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }

            if (onComplete != null)
                onComplete(response.StatusCode, result);

            return result;

        }

        /// <summary>
        /// URL拼写完整性检查
        /// </summary>
        /// <param name="url">待检查的URL</param>
        private static void UrlCheck(ref string url)
        {
            if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                url = "http://" + url;
        }
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏儿童编程

声音功能让儿童编程更有创造性

导读:Scratch中声音功能非常强大,除了常规的音效,你甚至可以模拟各种乐器的各个发音、设置节拍、休止……如果你愿意,甚至可以用它创作一个交响乐。我们可以引导...

13440
来自专栏儿童编程

儿童编程Scratch之“画笔”基础功能学习总结

Scratch中“画笔”功能能够让使用者模拟画笔在舞台上创作,合理运用能够给作品带来极大的趣味性。

65020
来自专栏儿童编程

一张图理清《梅花易数》梗概

学《易经》的目的不一定是为了卜卦,但是了解卜卦绝对能够让你更好地了解易学。今天用一张思维导图对《梅花易数》的主要内容进行概括,希望能够给学友们提供帮助。

30840
来自专栏Ken的杂谈

【系统设置】CentOS 修改机器名

17230
来自专栏儿童编程

儿童创造力教育与编程教育的碰撞——MIT雷斯尼克教授最新理论梗概

儿童编程教育已经在我国各一线二线城市疯狂出现,颇有“烂大街”的趋势。我们不禁要问很多很多问题:

21770
来自专栏儿童编程

我不是算命先生,却对占卜有了疑惑——如何论证“占卜前提”的正确与否

事出有因,我对《周易》感兴趣了很多年。只是觉得特别有趣,断断续续学习了一些皮毛。这几天又偶然接触到了《梅花易数》,觉得很是精彩,将五行八卦天干地支都串联了起来。...

13810
来自专栏儿童编程

一张导图梳理欧洲简史梗概

3.1K30
来自专栏儿童编程

《动物魔法学校》儿童学编程Scratch之“外观”部分

导读:本文通过一个案例《动物魔法学校》来学习Scratch语言的“外观”部分。之后通过一系列其他功能的综合运用对作品功能进行了扩展。

18640
来自专栏儿童编程

天干地支五行八卦的对应关系

18790
来自专栏儿童编程

什么样的人生才是有意义的人生——没有标准的标准答案

【导读】其实我们可以跳出这个小圈圈去更加科客观地看一下这个世界。在夜晚的时候我们仰望天空,浩瀚的宇宙中整个地球只是一粒浮尘,何况地球上一个小小的人类?在漫长的历...

1.7K50

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励