一个封装的 HttpClientHelper

public class EdiOFSRestHelper
    {
        public string appKey { get { return ""; } }
        public string appsecret { get { return ""; } }
        /// <summary>
        /// 返回结果格式
        /// </summary>
        public string format = "JSON";
        /// <summary>
        /// 接口版本
        /// </summary>
        public string v { get; set; }
        /// <summary>
        /// 签名
        /// </summary>
        public string sign { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        public string timestamp { get; set; }

        /// <summary>
        /// 应用参数
        /// </summary>
        public string ofs_param_json { get; set; }
        /// <summary>
        /// api接口名称
        /// </summary>
        public string api { get; set; }
        public string OFSApiUrl { get; set; }

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public EdiOFSRestHelper() { }

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="method">Rest方法名</param>
        /// <param name="version">版本(默认1.0)</param>
        /// <param name="apiUrl">服务地址(测试上线前需要将djapi改成:mockapi测试上线)</param>
        public EdiOFSRestHelper(string method, string json, string version = "1.0", string apiUrl = "")
        {
            timestamp = DateTime.Now.AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss");
            v = version;
            ofs_param_json = json;
            api = method;
            OFSApiUrl = apiUrl;
            string strXXX = $@"api{method}appKey{appKey}data{ofs_param_json}format{format}timestamp{timestamp}v{v}";
            string strSign = string.Format("{0}{1}{0}", appsecret, strXXX);
            sign = Des.MD5(strSign);
        }
        #endregion

        #region OFSGet请求
        /// <summary>
        /// OFSGet请求
        /// </summary>
        /// <returns></returns>
        public HttmResponseInfo Get()
        {
            HttmResponseInfo result = null;
            Dictionary<string, string> parame = new Dictionary<string, string>();
            parame.Add("api", api);
            parame.Add("appKey", appKey);
            parame.Add("format", format);
            parame.Add("data", ofs_param_json);
            parame.Add("timestamp", timestamp);
            parame.Add("v", v);
            parame.Add("sign", sign);

            StringBuilder strUrl = new StringBuilder(OFSApiUrl);
            int i = 0;
            foreach (var key in parame.Keys)
            {
                strUrl.AppendFormat("{0}{1}={2}", ++i > 1 ? "&" : "?", key, parame[key]);
            }

            HttpClientHelper client = new HttpClientHelper(strUrl.ToString());
            result = client.Get();

            return result;
        }
        #endregion

        #region OFSPost请求
        /// <summary>
        /// OFSPost请求
        /// </summary>
        /// <returns></returns>
        public HttmResponseInfo Post()
        {
            HttmResponseInfo result = null;
            Dictionary<string, string> parame = new Dictionary<string, string>();
            parame.Add("api", api);
            parame.Add("appKey", appKey);
            parame.Add("format", format);
            parame.Add("data", ofs_param_json);
            parame.Add("timestamp", timestamp);
            parame.Add("v", v);
            parame.Add("sign", sign);

            HttpClientHelper client = new HttpClientHelper(OFSApiUrl);
            result = client.Post(parame, false, "application/json");

            return result;
        }
        #endregion
    }
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

/// <summary>
/// 客户端Http操作帮助类
/// Author:William(徐威)
/// Create Time:2016-08-08
/// </summary>
public class HttpClientHelper
{
    #region 构造客户端Http操作帮助类静态对象
    private static HttpClientHelper instance = null;

    /// <summary>
    /// Http请求时间上限(毫秒,默认2分钟)
    /// </summary>
    public int TimeOut { get; set; }

    /// <summary>
    /// 接口地址
    /// </summary>
    public string ApiUrl { get; set; }

    /// <summary>
    /// 构造函数
    /// Author:William(徐威)
    /// Create Time:2016-08-08
    /// </summary>
    /// <param name="apiUrl">接口请求地址</param>
    /// <param name="timeOut">Http请求时间上限(毫秒,默认2分钟)</param>
    public HttpClientHelper(string apiUrl, int timeOut = 120000)
    {
        ApiUrl = apiUrl; // string.Format("{0}{1}format=json", apiUrl, apiUrl.IndexOf("?") == -1 ? "?" : "&");
        TimeOut = timeOut;
    }

    #endregion

    #region Get方式发起请求,返回Json字符串
    /// <summary>
    /// Get方式发起请求,返回Json字符串
    /// Author:William(徐威)
    /// Create Time:2016-08-08
    /// </summary>
    /// <param name="parameters">请求参数字典</param>
    /// <returns>Json字符串</returns>
    public HttmResponseInfo Get()
    {
        HttmResponseInfo result = new HttmResponseInfo();

        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ApiUrl);
            request.Timeout = TimeOut;
            request.Method = "GET";
            HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            result.Result = strBuilder.ToString();
        }
        catch (Exception ex)
        {
            result.IsSuccess = false;
            result.Result = "请求发生错误:" + ex.Message;
        }

        return result;
    }
    #endregion

    #region Post方式发起请求,返回Json字符串
    /// <summary>
    /// Post方式发起请求,返回Json字符串
    /// Author:William(徐威)
    /// Create Time:2016-08-08
    /// </summary>
    /// <param name="parameters">请求参数字典</param>
    /// <param name="UrlEncode">是否UrlEncode编码</param>
    /// <returns>Json字符串</returns>
    public HttmResponseInfo Post(IDictionary<string, string> parameters, bool UrlEncode = false,string ContentType= "application/x-www-form-urlencoded")
    {
        HttmResponseInfo result = new HttmResponseInfo();

        try
        {
            Encoding requestEncoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrl);
            request.Timeout = TimeOut;
            request.Method = "POST";
            request.ContentType = ContentType;

            #region 组装POST数据
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    string v = parameters[key];
                    if (UrlEncode == true)
                    {
                        v = HttpUtility.UrlEncode(parameters[key], Encoding.UTF8);//UrlEncode编码
                    }

                    buffer.AppendFormat("{0}{1}={2}", ++i > 1 ? "&" : string.Empty, key, v);
                }

                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            #endregion

            HttpWebResponse HttpWResp = (HttpWebResponse)request.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            result.Result = strBuilder.ToString();
        }
        catch (Exception ex)
        {
            result.IsSuccess = false;
            result.Result = "请求发生错误:" + ex.Message;
        }

        return result;
    }
    #endregion

    #region Post方式发起请求,返回Json字符串
    /// <summary>
    /// Post方式发起请求,返回Json字符串
    /// Author:William(徐威)
    /// Create Time:2016-03-02
    /// </summary>
    /// <param name="requestData">请求内容</param>
    /// <returns>Json字符串</returns>
    public HttmResponseInfo Post(string requestData)
    {
        HttmResponseInfo result = new HttmResponseInfo();

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(requestData);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(requestData);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            result.Result = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            result.Result = result.Result.Replace(Environment.NewLine, "");
            result.Result = result.Result.Replace("\r", "");
            result.Result = result.Result.Replace("\n", "");
        }
        catch (Exception ex)
        {
            result.IsSuccess = false;
            result.Result = string.Format("请求发生错误:{0}", ex.Message);
        }

        return result;
    }
    #endregion

    #region Get方式发起请求,返回Json字符串
    /// <summary>
    /// Get方式发起请求,返回Json字符串
    /// Author:William(徐威)
    /// Create Time:2016-03-02
    /// </summary>
    /// <param name="requestData">请求内容</param>
    /// <returns></returns>
    public HttmResponseInfo HttpGet(string requestData)
    {
        HttmResponseInfo result = new HttmResponseInfo();

        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}{2}", ApiUrl, (string.IsNullOrEmpty(requestData) ? "" : "?"), requestData));
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            result.Result = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
        }
        catch (Exception ex)
        {
            result.IsSuccess = false;
            result.Result = string.Format("请求发生错误:{0}" + ex.Message);
        }

        return result;
    }
    #endregion
}

 

/// <summary>
/// Http请求返回实体类
/// </summary>
public class HttmResponseInfo
{
    public HttmResponseInfo()
    {
        IsSuccess = true;
    }

    /// <summary>
    /// 请求是否成功(默认成功)
    /// </summary>
    public bool IsSuccess { get; set; }

    /// <summary>
    /// 返回Json字符串
    /// </summary>
    public string Result { get; set; }
}

 

一个封装的 HttpClientHelper

上一篇:解决jsp页面中直接使用request.set...方法报错问题


下一篇:https://hdlbits.01xz.net/wiki/Finding Bugs in Code答案