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

简介: 不错博客: [C#HttpHelper]官方产品发布与源码下载---苏飞版http://www.sufeinet.com/thread-3-1-1.html http://blog.csdn.net/xxj_jing/article/details/8107882 http://zhoufoxcn.

不错博客:

[C#HttpHelper]官方产品发布与源码下载---苏飞版
http://www.sufeinet.com/thread-3-1-1.html

http://blog.csdn.net/xxj_jing/article/details/8107882

http://zhoufoxcn.blog.51cto.com/792419/561934/

http://www.dedecms.com/knowledge/program/asp-donet/2012/0803/4214.html

http://blog.csdn.net/zhoufoxcn/article/details/6404236

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;
        }
    }
View Code

 

  

目录
相关文章
|
3月前
|
数据采集 存储 C#
C# 爬虫技术:京东视频内容抓取的实战案例分析
C# 爬虫技术:京东视频内容抓取的实战案例分析
|
5月前
|
编译器 API C#
技术心得记录:深入分析C#键盘勾子(Hook)拦截器,屏蔽键盘活动的详解
技术心得记录:深入分析C#键盘勾子(Hook)拦截器,屏蔽键盘活动的详解
|
2月前
|
前端开发 JavaScript
前端JS截取url上的参数
文章介绍了两种前端JS获取URL参数的方法:手动截取封装和使用URLSearchParams。
53 0
|
3月前
|
开发框架 前端开发 .NET
Asp.net Webapi 的 Post 方法不能把参数加到 URL 中?试试这样写
Asp.net Webapi 的 Post 方法不能把参数加到 URL 中?试试这样写
|
3月前
|
Java
JAVA 获取 URL 指定参数的值
JAVA 获取 URL 指定参数的值
48 0
|
5月前
|
C# Windows
C# 串口关闭时主界面卡死原因分析
串口程序关闭导致界面卡死的原因是主线程与辅助线程间的死锁。问题出在`SerialPort.Close()`方法与`DataReceived`事件处理程序。`DataReceived`事件在`lock (stream)`块中执行,而`Close()`方法会关闭`SerialStream`并锁定自身。当辅助线程处理数据并尝试更新UI时,UI线程因调用`Close()`被阻塞,造成死锁。解决办法是让`DataReceived`事件处理程序使用`this.BeginInvoke()`异步更新界面,避免等待UI线程,从而防止死锁。
|
4月前
|
JavaScript 前端开发 数据格式
URL编码【详解】——Javascript对URL进行编码解码的三种方式的区别和使用场景,axios请求拦截器中对get请求的参数全部进行URL编码
URL编码【详解】——Javascript对URL进行编码解码的三种方式的区别和使用场景,axios请求拦截器中对get请求的参数全部进行URL编码
255 0
|
4月前
|
JavaScript
js 获取并解析 url 中参数的三种方法
js 获取并解析 url 中参数的三种方法
466 0
|
5月前
|
存储 Java 编译器
C# 变量与参数详解
C# 变量与参数详解
|
5月前
|
文字识别 算法 API
视觉智能开放平台产品使用合集之在调用接口传入的图片URL参数,文件在本地或者非上海地域OSS链接,该怎么办
视觉智能开放平台是指提供一系列基于视觉识别技术的API和服务的平台,这些服务通常包括图像识别、人脸识别、物体检测、文字识别、场景理解等。企业或开发者可以通过调用这些API,快速将视觉智能功能集成到自己的应用或服务中,而无需从零开始研发相关算法和技术。以下是一些常见的视觉智能开放平台产品及其应用场景的概览。