zoukankan      html  css  js  c++  java
  • http请求代理类

    一、http请求代理类

    public class HttpProxy
    	{
    		/// <summary>
    		/// get请求
    		/// </summary>
    		/// <param name="url">接口地址</param>
    		/// <returns></returns>
    		public static string HttpGet(string url)
    		{
    			string result = string.Empty;
    			try
    			{
    				//创建http 请求
    				HttpWebRequest httpRequset = (HttpWebRequest)HttpWebRequest.Create(url);
    				httpRequset.Method = "GET";
    				httpRequset.ContentType = "text/html;charset=UTF-8";
    				httpRequset.Headers.Add("ignore-identity", "true");
    				HttpWebResponse response = (HttpWebResponse)httpRequset.GetResponse();
    				using (Stream responseStream = response.GetResponseStream())
    				{
    					using (StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
    					{
    						result = sReader.ReadToEnd();
    					}
    				}
    			}
    			catch (Exception ex)
    			{
    				throw ex;
    			}
    			return result;
    		}
    
    		/// <summary>
    		/// post请求
    		/// </summary>
    		/// <param name="url">接口地址</param>
    		/// <param name="paramData">json格式</param>
    		/// <param name="headerDic">自定义header信息</param>
    		/// <returns></returns>
    		public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null)
    		{
    			CookieContainer cookie = new CookieContainer();
    			string result = string.Empty;
    			try
    			{                               
                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    				HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
    				wbRequest.Headers.Add("ignore-identity", "true");
    				wbRequest.CookieContainer = cookie;
    				wbRequest.Method = "POST";
    				wbRequest.ContentType = "application/x-www-form-urlencoded";
    				wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
    				if (headerDic != null && headerDic.Count > 0)
    				{
    					foreach (var item in headerDic)
    					{
    						wbRequest.Headers.Add(item.Key, item.Value);
    					}
    				}
    				using (Stream requestStream = wbRequest.GetRequestStream())
    				{
    					using (StreamWriter swrite = new StreamWriter(requestStream))
    					{
    						swrite.Write(paramData);
    					}
    				}
    				HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
    				wbResponse.Cookies = cookie.GetCookies(wbResponse.ResponseUri);
    				using (Stream responseStream = wbResponse.GetResponseStream())
    				{
    					using (StreamReader sread = new StreamReader(responseStream))
    					{
    						result = sread.ReadToEnd();
    					}
    				}
    			}
    			catch (Exception ex)
    			{
    				throw ex;
    			}
    			return result;
    		}
    	}
    

    二、客户端调用

    public class RPCService
    	{
    		public dynamic GetRPCData()
    		{
    			var url = ConfigSettings.SubjectStatRpcUrl;// http://localhost:61558/stat/RpcService/SubjectStat.ashx
    			var par = new
    			{
    				functionName = "GetSubjectStatByProgress",
    				token = "c4b500e643f24dc78da2229e24557de3",
    				codeList = new List<int> { 9527, 1434 }
    			};
    			var parJson = System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(par));
    			parJson = $"cmd={parJson}";
    			//get 请求
    			var data = JsonConvert.DeserializeObject<dynamic>(HttpProxy.HttpGet($"{url}?{parJson}"));
    			// post 请求
    			var data1 = JsonConvert.DeserializeObject<dynamic>(HttpProxy.HttpPost(url, parJson));
    			return data;
    		}
    	}
    

     三、服务端代码

    public class SubjectStat : IHttpHandler
    	{
    		private ISubjectStatRpcService<dynamic> _iSubjectStatRpcService = new SubjectStatRpcService<dynamic>();
    
    		public void ProcessRequest(HttpContext context)
    		{
    
    			context.Response.ContentType = "application/json";
    			RpcService(context);
    		}
    
    		/// <summary>
    		/// 调用服务
    		/// </summary>
    		/// <param name="context"></param>
    		private void RpcService(HttpContext context)
    		{
    			try
    			{
    				//启用cmd={cname:"rpc",isAsync:true,functionName:"getDiscussByFile",fileCode:"",userId:""}
    				var command = Json.Decode(System.Web.HttpUtility.UrlDecode(context.Request["cmd"]));
    				// 方法名称
    				if (string.IsNullOrWhiteSpace(command.functionName))
    				{
    					context.Response.Write(Json.Encode(new HandlerResult(HttpStatusCode.InternalServerError, "参数funcName不能为空")));
    				}
    				// 登录验证暂时没有加,每个接口都传了一个token,是否需要验证是否登录
    				if (string.IsNullOrWhiteSpace(command.token))
    				{
    					context.Response.Write(Json.Encode(new HandlerResult(HttpStatusCode.InternalServerError, "参数token不能为空")));
    				}
    				//根据函数名调取相应的数据
    				switch (command.functionName.ToLower())
    				{
    					case "getsubjectstatbydeptlist"://按照部门统计
    						context.Response.Write(Json.Encode(GetSubjectStatByDeptList(command))); break;
    					case "getsubjectstatbyprogress"://按照课题研究进度统计
    						context.Response.Write(Json.Encode(GetSubjectStatByProgress(command))); break;
    					default:
    						context.Response.Write(Json.Encode(new HandlerResult(HttpStatusCode.InternalServerError, "调用的方法不存在"))); break;
    				}
    			}
    			catch (Exception ex)
    			{
    				context.Response.Write(Json.Encode(new HandlerResult(HttpStatusCode.InternalServerError, ex.Message)));
    			}
    		}
    
    		/// <summary>
    		/// 按照部门统计
    		/// </summary>
    		/// <returns></returns>
    		private HandlerResult GetSubjectStatByDeptList(dynamic par)
    		{
    			// 参数验证 Todo
    			var allCount = 0;
    			SubjectByDeptView totalRowData = new SubjectByDeptView();
    			var ret = new object();
    			return new HandlerResult(HttpStatusCode.OK, ret);
    		}
    
    		/// <summary>
    		/// 按照课题研究进度统计
    		/// </summary>
    		/// <returns></returns>
    		private HandlerResult GetSubjectStatByProgress(dynamic par)
    		{
    			// 参数验证 Todo
    
    			var allCount = 0;
    			SubjectByDeptView totalRowData = new SubjectByDeptView();
    			var ret = _iSubjectStatRpcService.GetSubjectStatByProgress(par);
    			return new HandlerResult(HttpStatusCode.OK, ret);
    		}
    
    		public bool IsReusable
    		{
    			get
    			{
    				return false;
    			}
    		}
    	}  
     
    调用https 协议地址时报错。 添加 调用create方法之前添加如下代码: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  • 相关阅读:
    git clone 慢,使用镜像
    Mysql 插入 path 插入不进去值
    os.walk 获取文件夹下所有的文件
    Manjaro安装后你需要这样做(仅有网址)
    Mysql 查询优化
    pandas df.to_csv 可保存为 txt 类型 index 设置索引 header 列名 sep 使用什么进行分隔
    pandas pd.to_markdown() 转换为 Markdown pd.to_latex() 转换为 latex
    pandas 读取txt seq分隔符类型 engine指定引擎 header 不将第一行作为列名
    pandas 读取文件时 header设置列名 index_col 设置索引 usecols 读取哪几列 parse_dates 将哪一列设置为时间类型 nrows 读取数据行数
    numpy cumprod 累乘 cumsum 累加 diff 和前一个元素做差值
  • 原文地址:https://www.cnblogs.com/zhuanjiao/p/12175924.html
Copyright © 2011-2022 走看看