HttpHelper.cs 4.9 KB
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using log4net;

namespace SmartShelf.Common
{
    public class HttpHelper
    {
        public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public static string Post(string url, string paramData)
        {
            return Post(url, paramData, Encoding.UTF8);
        }

        public static string Post(string url, string paramData, Encoding encoding)
        {
            if (paramData != "null" && paramData != null)
            {
                //   LogUtil.debug(LOGGER,  "HTTP POST to " + url + " \n\t >> " + paramData);
            }
            string result = "";

            if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
            {
                ServicePointManager.ServerCertificateValidationCallback =
                               new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
            }

            try
            {
                var wc = new MyWebClient(5000);
                if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
                    wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
                wc.Encoding = encoding;

                //paramData = Uri.EscapeDataString(paramData);
                result = wc.UploadString(url, "POST", paramData);
                //LogUtil.info(result);
            }
            catch (Exception e)
            {
                LogUtil.error("POST【" + paramData + "】 ERROR:" + e.StackTrace, 1);
            }
            if (!result.Contains("null") && result.Length != 0)
            {
                //LogUtil.debug(LOGGER,"receive << " + result);
            }
            return result;
        }

        public static string Get(string url)
        {
            return Get(url, Encoding.UTF8);
        }

        public static string Get(string url, Encoding encoding)
        {
            try
            {
                LogUtil.info(LOGGER, "HTTP GET FROM: " + url);
                var wc = new WebClient { Encoding = encoding };
                var readStream = wc.OpenRead(url);
                using (var sr = new StreamReader(readStream, encoding))
                {
                    var result = sr.ReadToEnd();
                    LogUtil.info(LOGGER, "receive << " + result);
                    return result;
                }
            }
            catch (Exception e)
            {
                LogUtil.error("HTTP GET ERROR:" + e.Message, 2);
            }
            return "";
        }

        public static string Get(string serverAddress, string path, Dictionary<string, object> map)
        {
            string param = GetParamStr(map);
            string allPath = serverAddress + path;
            if (param.Equals(""))
            {
                return HttpHelper.Get(allPath);
            }
            else
            {
                return HttpHelper.Get(allPath + "?" + param);
            }
        }

        public static string GetParamStr(Dictionary<string, object> map)
        {
            string str = "";
            foreach (string key in map.Keys)
            {
                if (str.Equals(""))
                {
                    str = key + "=" + map[key];
                }
                else
                {

                    str += "&" + key + "=" + map[key];
                }
            }
            return str;
        }


        public static Operation Post(string url, Operation operation)
        {
            try
            {
                string json = "";
                try
                {
                    json = JsonHelper.SerializeObject(operation);
                }
                catch (Exception ex)
                {
                    LOGGER.Error("JsonHelper.SerializeObject(operation) 出错【operation.op=" + operation.op + "】" + ex);
                }
                string result = Post(url, json);
                LOGGER.Debug("url【"+ url + "】【"+json+"】 result【"+result+"】" );
                if (!string.IsNullOrEmpty(result))
                {
                    try
                    {
                        return JsonHelper.DeserializeJsonToObject<Operation>(result);
                    }
                    catch (Exception ex)
                    {
                        LOGGER.Error("JsonHelper.DeserializeJsonToObject 出错【result=" + result + "】" + ex);
                    }
                }
            }
            catch (Exception ex)
            {
                LOGGER.Error("Post 出错【operation.op=" + operation.op + "】:" + ex);
            }
            return null;
        }

    }
}