C# Post HTTP Request

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Network;
using Newtonsoft.Json;


public static class HttpUtility
{

    /// <summary>
    /// 创建POST方式的HTTP请求  
    /// </summary>
    /// <param name="url"></param>
    /// <param name="parameters"></param>
    /// <param name="timeout"></param>
    /// <param name="userAgent"></param>
    /// <param name="cookies"></param>
    /// <returns></returns>
    public static HttpWebRequest CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
    {
        HttpWebRequest request = null;
        //如果是发送HTTPS请求  
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            request = WebRequest.Create(url) as HttpWebRequest;
        }
        else
        {
            request = WebRequest.Create(url) as HttpWebRequest;
        }
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        //设置代理UserAgent和超时
        //request.UserAgent = userAgent;
        request.Timeout = timeout; 

        if (cookies != null)
        {
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);
        }
        //发送POST数据  
        if (!(parameters == null || parameters.Count == 0))
        {
            StringBuilder buffer = new StringBuilder();
            int i = 0;
            foreach (string key in parameters.Keys)
            {
                if (i > 0)
                {
                    buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                }
                else
                {
                    buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    i++;
                }
            }
            byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
        }

        return request;
    }

    /// <summary>
    /// Post接口
    /// </summary>
    /// <param name="url"></param>
    /// <param name="parameters"></param>
    /// <param name="timeout"></param>
    /// <param name="userAgent"></param>
    /// <param name="cookies"></param>
    /// <returns></returns>
    public static async Task<T> PostHttpRequest(string url,IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
    {
        var req = CreatePostHttpResponse(url, parameters, timeout, userAgent, cookies);
        var res = await req.GetResponseAsync();
        if (null == res)
        {
            return null;
        }

        using (Stream s = res.GetResponseStream())
        {
            StreamReader reader = new StreamReader(s, Encoding.UTF8);

            var temp = reader.ReadToEnd();
            if (string.IsNullOrEmpty(temp))
            {
                return null;
            }
            return JsonConvert.DeserializeObject<T>(temp);
        }
    }
    

    /// <summary>
    /// MD5计算
    /// </summary>
    /// <param name="appKey"></param>
    /// <returns></returns>
    public static string Encrypt_MD5_UTF8(string appKey)
    {
        MD5 MD5 = new MD5CryptoServiceProvider();
        var datSource = Encoding.GetEncoding("utf-8").GetBytes(appKey);
        var newSource = MD5.ComputeHash(datSource);
        var sb = new StringBuilder(32);
        for (var i = 0; i < newSource.Length; i++)
        {
            sb.Append(newSource[i].ToString("x").PadLeft(2, '0'));
        }
        var crypt = sb.ToString();
        return crypt;
    }
}

 

posted @ 2018-03-05 18:47  MrBlue  阅读(452)  评论(0编辑  收藏  举报