zoukankan      html  css  js  c++  java
  • Http请求封装


    /****************************************************************************************
    ** 作者: Eddie Xu 
    ** 时间: 2018/4/10 10:51:40
    ** 版本: V1.0.0
    ** CLR: 4.0.30319.42000
    ** GUID: c44d9c85-7f03-4855-a8ea-8bfdeab6e4c2
    ** 机器名: DESKTOP-ECII567
    ** 描述: 尚未编写描述
    ****************************************************************************************/

    using Manjinba.Communication.Common.Logging;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;

    namespace Manjinba.Communication.Common.Utils
    {
    /// <summary>
    ///
    /// </summary>
    public class HttpUtils
    {
    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
    return true; //总是接受
    }

    #region Http Full Method
    /// <summary>
    /// 异步发送Http请求
    /// </summary>
    /// <param name="httpMethod"></param>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <param name="jsonBody"></param>
    /// <returns></returns>
    public static async Task<string> SendHttpMethod(string httpMethod, string url, Dictionary<string, string> head, Dictionary<string, object> query, string jsonBody = "")
    {
    string result = string.Empty;
    try
    {
    var resp = await AsyncHttpMethod(httpMethod, url, head, query, jsonBody);
    var responseStream = resp.GetResponseStream();
    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
    {
    result = reader.ReadToEnd();
    }
    }
    catch (WebException we)
    {
    var errorResult = string.Empty;
    var exceptonStream = we.Response.GetResponseStream();
    using (StreamReader reader = new StreamReader(exceptonStream, Encoding.UTF8))
    {
    errorResult = reader.ReadToEnd();
    }
    LogHelper.GetLog().Error(errorResult + "||" + we.StackTrace);
    }
    return result;
    }
    /// <summary>
    /// 汇总所有Http请求方法
    /// </summary>
    /// <param name="httpMethod"></param>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <param name="jsonBody"></param>
    /// <returns></returns>
    public static async Task<WebResponse> AsyncHttpMethod(string httpMethod, string url, Dictionary<string, string> head, Dictionary<string, object> query, string jsonBody = "")
    {
    if (string.IsNullOrWhiteSpace(httpMethod))
    {
    throw new ArgumentNullException("httpMethod");
    }
    if (string.IsNullOrWhiteSpace(url))
    {
    throw new ArgumentNullException("url");
    }
    string queryString = url.Contains("?") ? "&" : "?";
    foreach (var parameter in query)
    {
    queryString += parameter.Key + "=" + parameter.Value + "&";
    }
    queryString = queryString.Substring(0, queryString.Length - 1);
    HttpWebRequest httpWebRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    httpWebRequest = WebRequest.Create(url + queryString) as HttpWebRequest;
    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url + queryString);
    }
    httpWebRequest.ContentType = "application/json; charset=utf-8";
    httpWebRequest.Method = httpMethod.ToUpper();
    httpWebRequest.KeepAlive = true;
    httpWebRequest.Timeout = 8000;
    httpWebRequest.ServicePoint.Expect100Continue = false;
    httpWebRequest.Proxy = null;
    foreach (var dic in head)
    {
    httpWebRequest.Headers.Add(dic.Key, dic.Value);
    }
    if (!string.IsNullOrWhiteSpace(jsonBody))
    {
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonBody);
    //设置请求的 ContentLength
    httpWebRequest.ContentLength = bytes.Length;
    //获得请 求流
    try
    {
    Stream stream = await httpWebRequest.GetRequestStreamAsync();// Gets awaited here indefinitely till the first que of 2 completes their GetResponseAsync() call below
    stream.Write(bytes, 0, bytes.Length);
    await stream.FlushAsync();
    }
    catch (Exception e)
    {
    LogHelper.GetLog().Error(e.Message + e.StackTrace);
    }
    }

    var response = await httpWebRequest.GetResponseAsync();
    return response;
    }
    #endregion Http Full Method

    #region Http Put Method
    /// <summary>
    /// 异步发送Put请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <returns></returns>
    public static async Task<string> Put(string url, Dictionary<string, string> head, string query)
    {
    string result = string.Empty;
    try
    {
    var resp = await AsyncPut(url, head, query);
    var responseStream = resp.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
    {
    result = reader.ReadToEnd();
    }
    }
    catch (WebException we)
    {
    var errorResult = string.Empty;
    var exceptonStream = we.Response.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(exceptonStream, Encoding.UTF8))
    {
    errorResult = reader.ReadToEnd();
    }
    LogHelper.GetLog().Error(errorResult + "||" + we.StackTrace);
    }
    return result;
    }
    /// <summary>
    /// 发送Put请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <returns></returns>
    public static async Task<WebResponse> AsyncPut(string url, Dictionary<string, string> head, string query)
    {
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(query);
    HttpWebRequest webRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    webRequest = WebRequest.Create(url) as HttpWebRequest;
    webRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    }
    // HTTPS请求
    webRequest.Method = "PUT";
    webRequest.KeepAlive = true;
    webRequest.Timeout = 8000;
    webRequest.ServicePoint.Expect100Continue = false;
    //webRequest.ServicePoint.ConnectionLimit = 65500;
    webRequest.Proxy = null;
    foreach (var dic in head)
    {
    webRequest.Headers.Add(dic.Key, dic.Value);
    //webRequest.Headers.Add("Authorization", "test");
    //webRequest.Headers.Add(HttpRequestHeader.Authorization,"");
    }

    //设置请求的 ContentLength
    webRequest.ContentLength = bytes.Length;
    webRequest.ContentType = "application/json; charset=utf-8";
    //获得请 求流
    Stream stream = await webRequest.GetRequestStreamAsync();// Gets awaited here indefinitely till the first que of 2 completes their GetResponseAsync() call below
    stream.Write(bytes, 0, bytes.Length);
    await stream.FlushAsync();

    var response = await webRequest.GetResponseAsync();
    return response;
    }
    #endregion Http Put Method

    #region Http Post Method
    /// <summary>
    /// 异步发送Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <returns></returns>
    public static async Task<string> Post(string url, Dictionary<string, string> head, string query)
    {
    string result = string.Empty;
    try
    {
    var resp = await AsyncPost(url, head, query);
    var responseStream = resp.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
    {
    result = reader.ReadToEnd();
    }
    }
    catch (WebException we)
    {
    var errorResult = string.Empty;
    var exceptonStream = we.Response.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(exceptonStream, Encoding.UTF8))
    {
    errorResult = reader.ReadToEnd();
    }
    LogHelper.GetLog().Error(errorResult + "||" + we.StackTrace);
    }
    return result;
    }
    /// <summary>
    /// 发送Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <returns></returns>
    public static async Task<WebResponse> AsyncPost(string url, Dictionary<string, string> head, string query)
    {
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(query);
    HttpWebRequest webRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    webRequest = WebRequest.Create(url) as HttpWebRequest;
    webRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    }
    // HTTPS请求
    webRequest.Method = "POST";
    webRequest.KeepAlive = true;
    webRequest.Timeout = 8000;
    webRequest.ServicePoint.Expect100Continue = false;
    //webRequest.ServicePoint.ConnectionLimit = 65500;
    webRequest.Proxy = null;
    foreach (var dic in head)
    {
    webRequest.Headers.Add(dic.Key, dic.Value);
    //webRequest.Headers.Add("Authorization", "test");
    //webRequest.Headers.Add(HttpRequestHeader.Authorization,"");
    }

    //设置请求的 ContentLength
    webRequest.ContentLength = bytes.Length;
    webRequest.ContentType = "application/json; charset=utf-8";
    //获得请 求流
    Stream stream = await webRequest.GetRequestStreamAsync();// Gets awaited here indefinitely till the first que of 2 completes their GetResponseAsync() call below
    stream.Write(bytes, 0, bytes.Length);
    await stream.FlushAsync();

    var response = await webRequest.GetResponseAsync();
    return response;
    }
    /// <summary>
    /// 发送Post请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <returns></returns>
    public static async Task<string> OldPost(string url, Dictionary<string, string> head, string query)
    {
    string result = null;
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(query);
    HttpWebRequest webRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    webRequest = WebRequest.Create(url) as HttpWebRequest;
    webRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    }
    webRequest.Method = "POST";
    webRequest.Timeout = 8000;
    webRequest.KeepAlive = true;
    webRequest.ServicePoint.Expect100Continue = false;
    //webRequest.ServicePoint.ConnectionLimit = 65500;
    webRequest.Proxy = null;
    foreach (var dic in head)
    {
    webRequest.Headers.Add(dic.Key, dic.Value);
    }

    //设置请求的 ContentLength
    webRequest.ContentLength = bytes.Length;
    webRequest.ContentType = "application/json; charset=utf-8";
    //获得请 求流
    Stream stream = await webRequest.GetRequestStreamAsync();// Gets awaited here indefinitely till the first que of 2 completes their GetResponseAsync() call below
    stream.Write(bytes, 0, bytes.Length);
    await stream.FlushAsync();

    var responseStream = (Stream)await webRequest.GetRequestStreamAsync();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
    {
    result = reader.ReadToEnd();
    }

    stream.Close();
    stream.Dispose();
    return result;
    }
    #endregion Http Post Method

    #region Http Get Method
    /// <summary>
    /// 异步发送Get请求
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="query"></param>
    /// <param name="jsonBody"></param>
    /// <returns></returns>
    public static async Task<string> Get(string url, Dictionary<string, string> head, Dictionary<string, object> query, string jsonBody = "")
    {
    string result = string.Empty;
    try
    {
    var resp = await AsyncGet(url, head, query, jsonBody);
    var responseStream = resp.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
    {
    result = reader.ReadToEnd();
    }
    }
    catch (WebException we)
    {
    var errorResult = string.Empty;
    var exceptonStream = we.Response.GetResponseStream();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(exceptonStream, Encoding.UTF8))
    {
    errorResult = reader.ReadToEnd();
    }
    LogHelper.GetLog().Error(errorResult + "||" + we.StackTrace);
    }
    return result;
    }
    /// <summary>
    /// 发送Http Get请求,获取返回信息
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="parameters"></param>
    /// <param name="jsonBody"></param>
    /// <returns></returns>
    public static async Task<WebResponse> AsyncGet(string url, Dictionary<string, string> head, Dictionary<string, object> parameters, string jsonBody = "")
    {
    string queryString = url.Contains("?") ? "&" : "?";
    foreach (var parameter in parameters)
    {
    queryString += parameter.Key + "=" + parameter.Value + "&";
    }
    queryString = queryString.Substring(0, queryString.Length - 1);
    HttpWebRequest httpWebRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    httpWebRequest = WebRequest.Create(url + queryString) as HttpWebRequest;
    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url + queryString);
    }
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "GET";
    httpWebRequest.Timeout = 20000; // Http请求默认超时时间20秒
    foreach (var dic in head)
    {
    httpWebRequest.Headers.Add(dic.Key, dic.Value);
    }
    if (!string.IsNullOrWhiteSpace(jsonBody))
    {
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonBody);
    //设置请求的 ContentLength
    httpWebRequest.ContentLength = bytes.Length;
    //获得请 求流
    Stream stream = await httpWebRequest.GetRequestStreamAsync();// Gets awaited here indefinitely till the first que of 2 completes their GetResponseAsync() call below
    stream.Write(bytes, 0, bytes.Length);
    await stream.FlushAsync();
    }
    var response = await httpWebRequest.GetResponseAsync();
    return response;
    }
    #endregion Http Get Method

    /// <summary>
    /// 发送Http Post请求,获取返回信息
    /// body是要传递的参数
    /// post的cotentType填写:"application/x-www-form-urlencoded" soap填写:"text/xml; charset=utf-8"
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="body"></param>
    /// <param name="contentType"></param>
    /// <returns></returns>
    public static string HttpPost(string url, Dictionary<string, string> head, string body, string contentType)
    {
    System.GC.Collect();
    HttpWebRequest webRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    webRequest = WebRequest.Create(url) as HttpWebRequest;
    webRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    }
    //HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.ContentType = contentType;
    webRequest.Method = "POST";
    webRequest.KeepAlive = true;
    webRequest.ServicePoint.Expect100Continue = false;
    //webRequest.ServicePoint.ConnectionLimit = 65500;
    webRequest.Timeout = 20000; // Http请求默认超时时间20秒
    webRequest.Proxy = null;

    foreach (var dic in head)
    {
    webRequest.Headers.Add(dic.Key, dic.Value);
    }

    byte[] btBodys = Encoding.UTF8.GetBytes(body);
    webRequest.ContentLength = btBodys.Length;
    using (Stream stream = webRequest.GetRequestStream())
    {
    stream.Write(btBodys, 0, btBodys.Length);
    }
    HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
    string responseContent = streamReader.ReadToEnd();

    streamReader.Close();
    httpWebResponse.Close();
    webRequest.Abort();

    return responseContent;
    }
    /// <summary>
    /// 发送Http Get请求,获取返回信息
    /// </summary>
    /// <param name="url"></param>
    /// <param name="head"></param>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public static string HttpGet(string url, Dictionary<string, string> head, Dictionary<string, object> parameters)
    {
    string queryString = "?";
    foreach (var parameter in parameters)
    {
    queryString += parameter.Key + "=" + parameter.Value + "&";
    }
    queryString = queryString.Substring(0, queryString.Length - 1);

    HttpWebRequest httpWebRequest = null;
    //如果是发送HTTPS请求
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
    httpWebRequest = WebRequest.Create(url + queryString) as HttpWebRequest;
    httpWebRequest.ProtocolVersion = HttpVersion.Version10;
    }
    else
    {
    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url + queryString);
    }
    //HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "GET";
    httpWebRequest.Timeout = 20000; // Http请求默认超时时间20秒

    foreach (var dic in head)
    {
    httpWebRequest.Headers.Add(dic.Key, dic.Value);
    }

    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
    string responseContent = streamReader.ReadToEnd();

    httpWebRequest.Abort();
    streamReader.Close();
    httpWebResponse.Close();
    return responseContent;

    }

    }
    }

  • 相关阅读:
    hdu 4614 线段树 二分
    cf 1066d 思维 二分
    lca 最大生成树 逆向思维 2018 徐州赛区网络预赛j
    rmq学习
    hdu 5692 dfs序 线段树
    dfs序介绍
    poj 3321 dfs序 树状数组 前向星
    cf 1060d 思维贪心
    【PAT甲级】1126 Eulerian Path (25分)
    【PAT甲级】1125 Chain the Ropes (25分)
  • 原文地址:https://www.cnblogs.com/Nine4Cool/p/10540682.html
Copyright © 2011-2022 走看看