栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

c# .net 模拟请求 POST, Get,Put,Delete,并带Headers,BUF加持异步多线程执行

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c# .net 模拟请求 POST, Get,Put,Delete,并带Headers,BUF加持异步多线程执行

你可能还需要

c# .net http Post请求 发送Json数据

c# .net http Post请求 发送Json数据_橙cplvfx-技术踩坑记-CSDN博客c# .net http Post请求 发送Json数据https://cplvfx.blog.csdn.net/article/details/121760580

 示例Post 调用 Post 调用,带Header
string url = "http://baidu.com/api/AddUser";
string postData = $"UserName=Miaoming&Age=26";
Hashtable headht = new Hashtable();
headht.Add("UserTokenStr", "key123456");
string Res = HttpMethods.HttpPost(url, postData, headht);
Post 调用,不带Header
string url = "http://baidu.com/api/AddUser";
string postData = $"UserName=Miaoming&Age=26";
string Res = HttpMethods.HttpPost(url, postData);

示例 Get调用 Get调用,带Header
int ID=123;
string url = "http://baidu.com/api/GetUser?ID=" + ID + "&age=16";
Hashtable headht = new Hashtable();
headht.Add("UserTokenStr", "key123456"); 
UserInfoMode userInfo = HttpMethods.HttpGet(url,headht);

Get调用,不带Header
int ID=123;
string url = "http://baidu.com/api/GetUser?ID=" + ID + "&age=16";
UserInfoMode userInfo = HttpMethods.HttpGet(url);

完整帮助类
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
 

namespace Quanxi.Yijiao.Mob.App_Tools
{
    public class HttpHelp
    {
        #region POST

        /// 
        /// HTTP POST方式请求数据
        /// 
        /// URL.
        /// POST的数据
        /// 请求头参数
        /// 
        public static string HttpPost(string url, string param = null, Hashtable headht = null)
        {
            HttpWebRequest request;

            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "**";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }
        #endregion

        #region Delete
        /// 
        /// HTTP Delete方式请求数据.
        /// 
        /// URL.
        /// 
        public static string HttpDelete(string url, string param = null)
        {
            HttpWebRequest request;

            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "Delete";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "**";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            WebResponse response = null;
            string responseStr = null;
            if (headht != null)
            {
                foreach (DictionaryEntry item in headht)
                {
                    request.Headers.Add(item.Key.ToString(), item.Value.ToString());
                }
            }

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return responseStr;
        }
        public static string HttpGet(string url, Encoding encodeing, Hashtable headht = null)
        {
            HttpWebRequest request;

            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            WebResponse response = null;
            string responseStr = null;
            if (headht != null)
            {
                foreach (DictionaryEntry item in headht)
                {
                    request.Headers.Add(item.Key.ToString(), item.Value.ToString());
                }
            }

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), encodeing);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            return responseStr;
        }
        #endregion

        #region Post With Pic
        private string HttpPost(string url, IDictionary param, string filePath)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "rn");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();
            string responseStr = null;

            string formdataTemplate = "Content-Disposition: form-data; name="{0}"rnrn{1}";
            foreach (string key in param.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, param[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"rnContent-Type: {2}rnrn";
            string header = string.Format(headerTemplate, "pic", filePath, "text/plain");
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "--rn");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                responseStr = reader2.ReadToEnd();
                //logger.Debug(string.Format("File uploaded, server response is: {0}", responseStr));
            }
            catch (Exception ex)
            {
                //logger.Error("Error uploading file", ex);
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                throw;
            }
            return responseStr;
        }
        #endregion

        #region Post With Pic
        /// 
        /// HTTP POST方式请求数据(带图片)
        /// 
        /// URL        
        /// POST的数据
        /// 图片
        /// 
        public static string HttpPost(string url, IDictionary param, byte[] fileByte)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "rn");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();
            string responseStr = null;

            string formdataTemplate = "Content-Disposition: form-data; name="{0}"rnrn{1}";
            foreach (string key in param.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, param[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}"rnContent-Type: {2}rnrn";
            string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");//image/jpeg
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            rs.Write(fileByte, 0, fileByte.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "--rn");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                responseStr = reader2.ReadToEnd();
                // logger.Error(string.Format("File uploaded, server response is: {0}", responseStr));
            }
            catch (Exception ex)
            {
                //logger.Error("Error uploading file", ex);
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
                throw;
            }
            return responseStr;
        }
        #endregion

        #region HttpsClient
        /// 
        /// 创建HttpClient
        /// 
        /// 
        public static HttpClient CreateHttpClient(string url)
        {
            HttpClient httpclient;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                httpclient = new HttpClient();
            }
            else
            {
                httpclient = new HttpClient();
            }
            return httpclient;
        }
        #endregion 
    }
}

BUF加持异步多线程执行 RequestFactory:封装的异步--开辟新的线程请求
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace Quanxi.Yijiao.Mob.App_Tools
{
    /// 
    /// 请求工厂
    /// 
    public class RequestFactory
    {
        /// 
        /// HTTP GET方式请求数据.
        /// 
        /// URL
        /// 请求头参数
        /// 
        public static async Task HttpGet(string url, Hashtable headht = null)
        {
            string result = "";
            await Task.Run(() =>
            {
                try
                {
                    result = HttpHelp.HttpGet(url, headht);
                }
                catch (Exception e)
                {
                    result = e.Message;
                }
            });
            return result;
        }

        /// 
        /// HTTP POST方式请求数据
        /// 
        /// URL.
        /// POST的数据
        /// 请求头参数
        /// 
        public static async Task HttpPost(string url, string param = null, Hashtable headht = null)
        {

            string result = "";
            await Task.Run(() =>
            {
                try
                {
                    result = HttpHelp.HttpPost(url, param, headht);
                }
                catch (Exception e)
                {
                    result = e.Message;
                }
            });
            return result;
        }
    }
}

asp.net MVC调用
public async Task Index()
{
	try
	{
		Console.WriteLine("业务--开始");

		string url1 = "http://xxx.xxx.xx/data?act=region_list&pcode=0&level=1";//地域列表 

		string url2 = "http://xxx.xxx.xx/data?SiteName=yijiao&PageID=4&LocationID=4";//广告接口 

		string url3 = "http://xxx.xxx.xx/data?SiteName=kangyang&num=30";//友情链接接口 

	   string addJson ="";//地域列表
	   string adJson = "";//广告列表
	   string linkJson = "";//友情链接列表 
		 
		await Task.Run(() =>
		{
			Task tStr1 = RequestFactory.HttpGet(url1);
			Task tStr2 = RequestFactory.HttpGet(url2);
			Task tStr3 = RequestFactory.HttpGet(url3);
			 addJson = tStr1.Result;//地域列表
			 adJson = tStr2.Result;//广告列表
			 linkJson = tStr3.Result;//友情链接列表 
		});


		Console.WriteLine("业务-结束-----2");
	}
	catch (Exception e)
	{

		throw;
	}
	ViewBag.result = "666666666666";
	return View();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号