C# HTTP工具HttpHelper

C# HTTP工具HttpHelperC#HTTP工具HttpHelper新建文件名HttpHelper.cs代码如下:usingNewtonsoft.Json;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Net;

大家好,欢迎来到IT知识分享网。C#

C# HTTP工具HttpHelper

  • 新建文件名HttpHelper.cs

代码如下:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace ME.Muphy.Util
{
    public static class HttpHelper
    {
        ///
        /// Get请求
        /// 
        public static HttpWebResponse CreateGetHttpResponse(string url, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = contentType;
            if (userAgent != null)
            {
                request.UserAgent = userAgent;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            if (timeout > 0)
            {
                request.Timeout = timeout * 1000;
            }
            if (headers != null)
            {
                request.Headers.Add(headers);
            }
            request.Timeout = timeout;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return response;
        }

        ///
        /// Get请求
        /// 
        public static string GetHttpResponse(string url, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebResponse response = CreateGetHttpResponse(url, timeout, contentType, cookies, headers, userAgent);
            return GetResponseString(response);
        }

        /// <summary>
        /// 创建POST方式的HTTP请求
        /// timeout 单位(秒/s)
        /// </summary>
        public static HttpWebResponse CreatePostHttpResponse(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies =  null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebRequest request = null;
            if (userAgent != null)
            {
                request.UserAgent = userAgent;
            }
            //如果是发送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 = contentType;
            if (timeout > 0)
            {
                request.Timeout = timeout * 1000;
            }
            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            if(headers != null)
            {
                request.Headers.Add(headers);
            }
            Console.WriteLine("请求路径:" + url);
            //发送POST数据  
            if (json != null)
            {
                var body = "";
                if (typeof(IConvertible).IsAssignableFrom(json.GetType()))
                {
                    body = Convert.ToString(json);
                }
                else
                {
                    body = JsonConvert.SerializeObject(json);
                    // 这里默认 contentType = "application/json" 下面只是简单的处理application/x-www-form-urlencoded
                    if (contentType != null && contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                    {
                        Dictionary<string, string> d = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in d)
                        {
                            sb.Append("&").Append(item.Key).Append("=").Append(item.Value);
                        }
                        if (sb.Length > 0)
                        {
                            sb.Remove(0, 1);
                        }
                        body = sb.ToString();
                    }
                }
                byte[] data = Encoding.UTF8.GetBytes(body);
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }



        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        public static string PostHttpResponse(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            HttpWebResponse response = CreatePostHttpResponse(url, json, timeout, contentType, cookies, headers, userAgent);
            return GetResponseString(response);
        }

        /// <summary>
        /// 创建POST方式的HTTP请求
        /// </summary>
        public static ResponseResult<T> PostHttpResponse<T>(string url, object json, int timeout = 60, string contentType = "application/json", CookieCollection cookies = null, WebHeaderCollection headers = null, string userAgent = null)
        {
            string response = PostHttpResponse(url, json, timeout, contentType, cookies, headers, userAgent);
            Console.WriteLine("POST:" + url + ", 请求结果:" + response);
            if (string.IsNullOrEmpty(response))
            {
                return new ResponseResult<T>();
            }
            var rr = JsonConvert.DeserializeObject<ResponseResult<T>>(response);
            return rr;
        }


        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
    }

    public partial class ResponseResult<T>
    {
        public int c = 500;
        public string m = "未知错误";

        /// <summary>
        /// 返回值编码,参见返回状态编码表
        /// </summary>
        public int code
        {
            get
            {
                return c;
            }
            set
            {
                c = value;
            }
        }

        /// <summary>
        /// 返回提示信息,如具体错误信息
        /// </summary>
        public string msg
        {
            get
            {
                return m;
            }
            set
            {
                m = value;
            }
        }

        /// <summary>
        /// 返回成功时携带的部分数据
        /// </summary>
        public T data { get; set; }
    }
}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/31159.html

(0)
上一篇 2023-10-31 15:00
下一篇 2023-11-15 14:15

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信