原创

C#-积累-C#中实现GET、POST请求中转-HttpTool

using cn.jiangjiesheng.auth;
using cn.jiangjiesheng.tool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using WebHelper;

namespace AotuBusiness
{
    public class HttpTool
    {
        /// <summary>
        /// 用法注意见《C#-积累-MVC框架中Controller中的方法获取不到post数据-HttpContext.Current.Request[key]》
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static String GetString(String key)
        {
            HttpContext context = HttpContext.Current;
            String value = context.Request[key];//.ToLower().ToString();

            return !String.IsNullOrEmpty(value) ? value : null;//允许空格
        }

        /// <summary>
        /// 用法注意见《C#-积累-MVC框架中Controller中的方法获取不到post数据-HttpContext.Current.Request[key]》
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Int32 GetInt32(String key)
        {
            HttpContext context = HttpContext.Current;
            String v = GetString(key);
            if (v == null || !ValueVarify.isNumberic(v))
            {
                return -1000;
            }
            return Convert.ToInt32(v);
        }

        /// <summary>
        /// 用法注意见《C#-积累-MVC框架中Controller中的方法获取不到post数据-HttpContext.Current.Request[key]》
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Int64 GetInt64(String key)// Long 类型
        {
            HttpContext context = HttpContext.Current;
            String v = GetString(key);
            if (v == null || !ValueVarify.isNumberic(v))
            {
                return -1000;
            }
            return Convert.ToInt64(v);
        }


        public static bool IsPost()
        {
            if (HttpContext.Current.Request.HttpMethod == "POST")
            {
                return true;
            }
            return false;
        }
        public static bool IsOptions()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                return true;
            }
            return false;
        }
        public static void WriteResponse<T>(ServerResponse<T> Response)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                context.Response.ContentType = "application/json";
                context.Response.Write(JsonHelper.ObjectToJsonForSerialize(Response));
                context.Response.End();
            }
        }

        /// <summary>
        /// 这个post 可用 不支持json 参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <returns></returns>
        public static string HttpPostWithJson(string url, String jsonPost, Dictionary<string, string> headerDic = null)
        {
            string result = string.Empty;
            string paramData = jsonPost;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/json";

                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            { }

            return result;
        }

        /// <summary>
        /// 这个post 可用 不支持json 参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramData"></param>
        /// <param name="headerDic"></param>
        /// <returns></returns>
        public static string HttpPost(string url, Dictionary<string, string> parameters, Dictionary<string, string> headerDic = null)
        {
            string result = string.Empty;
            string paramData = BuildPostQuery(parameters);
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/x-www-form-urlencoded";



                wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
                if (headerDic != null && headerDic.Count > 0)
                {
                    foreach (var item in headerDic)
                    {
                        wbRequest.Headers.Add(item.Key, item.Value);
                    }
                }
                using (Stream requestStream = wbRequest.GetRequestStream())
                {
                    using (StreamWriter swrite = new StreamWriter(requestStream))
                    {
                        swrite.Write(paramData);
                    }
                }
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sread = new StreamReader(responseStream))
                    {
                        result = sread.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            { }

            return result;
        }
        public static string HttpGet(string url)
        {
            string result = string.Empty;
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Method = "GET";
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(responseStream))
                    {
                        result = sReader.ReadToEnd();
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }

        /// <summary>
        /// 可能有问题。请求过程中数据被修改? 测试失败
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPostNotTest(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            //request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildPostQuery(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();
        }

    }

}
正文到此结束
本文目录