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

不错博客:

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

  

时间: 2024-10-10 07:27:49

C#分析URL参数获取参数和值得对应列表(二)的相关文章

JavaScript从URL里面获取参数

如何从URL中获取参数是一个很基本的问题.首先假定URL是合法的,code 如下,欢迎各位大大code review. 1. 可以使用一个match和循环split function findQueriesFromUrl(url){ var regex, matches, i, length, pair, result = {}, query; if(!url) return; regex = /\w+\=\w*/g; matches = url.match(regex); for(i = 0,

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

C#操作Url参数 http://www.cnblogs.com/RobotH/archive/2008/11/17/1335322.html 用 C# 分析 URL 中的参数信息 http://www.cnblogs.com/rchen/archive/2005/06/23/179627.html C#获取URL参数值 http://www.cnblogs.com/gaizai/archive/2010/05/27/1743485.html http://outofmemory.cn/code

Forever.Sun 从URL地址获取参数

-----------------------------js版本--------------------------------------- function Request(para) { para = para.toLowerCase(); var url = document.URL; var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&"); var k

小程序 循环遍历 传参数 获取参数的方法

//循环操作 block包裹着被循环的模板 <block wx:for="{{post_content}}" wx:for-item="item" wx:for-index="index" wx:key="index"> <!-- {{...item}}展开这个对象 --> <!-- data-postId={{item.postId}}自定义属性 --> <view catchtap

控制台程序console输入参数 获取参数

class Program    {        static void Main(string[] args)        {                                 if (args.Length > 0)                Console.WriteLine(args[args.Length - 1]); //cd到控制台编译的debug文件夹 输入 Redis.exe 111 aaa ddd 打印出:ddd            Console.R

C#分析URL参数并获取参数和值对应列表的方法

本文实例讲述了C#分析URL参数获取参数和值对应列表的方法.分享给大家供大家参考.具体分析如下: 这个C#函数用于分析url中传递的所有参数,输出一个参数名和参数值对应的NameValueCollection列表,经常能用得到 /// <summary> /// 分析 url 字符串中的参数信息 /// </summary> /// <param name="url">输入的 URL</param> /// <param name=

Linux - Shell - 参数获取

概述 参数 背景 复习一下 shell 脚本的参数获取 场景 os centos7 1. 参数: 基础 概述 简单描述 参数 1. 获取参数 获取 第一个 参数 获取参数 使用 ${num} 获取参数 ${1} 获取 第一个参数 代码 #!/bin/bash var1=${1} echo ${var1} 其他 可以尝试 ${2}, ${3} 等获取后续参数 默认情况下, 如果参数不足, echo 不会报错, 其他命令, 需要验证 2. 获取多个参数 问题1: 获取多个参数 一个一个获取参数, 如

js获取url传递的参数

获取URL带参数的JAVASCRIPT客户端解决方案 一.正则分析法.(我较喜欢使用正则)function GetQueryString(name) {var reg = new RegExp(“(^|&)” + name + “=([^&]*)(&|$)”,”i”);var r = window.location.search.substr(1).match(reg);if (r!=null) return (r[2]); return null;}alert(GetQueryS

url参数获取

index.htm?参数1=数值1&参数2=数值2&参数3=数据3&参数4=数值4&...... 静态html文件js读取url参数,根据获取html的参数值控制html页面输出. 一.字符串分割分析法. 这里是一个获取URL带REQUESTRING参数的JAVASCRIPT客户端解决方案. 相当于asp的request.querystring,PHP的$_GET,jsp的request.getParameter //var USERCODE="<%=req