C# HttpWebRequest 异步请求

C# HttpWebRequest 异步请求异步请求://定义委托publicdelegatevoidAsyncdelegate(WebProxyobjName);//异步调用完成时,执行回调方法privatevoidCallbackMethod(IAsyncResultar){ Asyncdelegatedlgt=(Asyncdelegate)ar.AsyncState; dlgt.EndInvoke(a

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

同事古X强帮忙实现的一个功能,记录下来,方便以后查阅

异步请求:

//定义委托
public delegate void Asyncdelegate(WebProxy objName);

//异步调用完成时,执行回调方法
private void CallbackMethod(IAsyncResult ar)
{
	Asyncdelegate dlgt = (Asyncdelegate)ar.AsyncState;
	dlgt.EndInvoke(ar);
}

//异步调用Commit方法
public virtual void Run()
{
	Asyncdelegate isgt = new Asyncdelegate(Commit);
	IAsyncResult ar = isgt.BeginInvoke(null,new AsyncCallback(CallbackMethod),isgt);
}

HttpWebRequest请求:

//向APM接口提交数据
//为什么要用WebProxy,因为.Net 4.0以下没有Host属性,无法设置标头来做DNS重连
public virtual void Commit(WebProxy objName = null)
{
	string ret = string.Empty;
	string ip = string.Empty;
	try
	{
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
		request.Method = "POST";//
		request.Timeout = 30000;
		request.ContentType = "application/x-www-form-urlencoded";
		request.ServicePoint.Expect100Continue = false;
		if(objName != null)
		{
			request.Proxy = objName;
		}
		byte[] byteArray = Encoding.UTF8.GetBytes("&a=要发送的数据&b=要发送的数据");
		request.ContentLength = byteArray.Length;
		Stream dataStream = request.GetRequestStream();
		dataStream.Write(byteArray,0,byteArray.Length);
		dataStream.Close();
		WebResponse response = request.GetResponse();
		dataStream = request.GetResponseStream();
		StreamReader reader = new StreamReader(dataStream);
		string responseFromServer = reader.ReadToEnd();
		reader.Close();
		dataStream.Close();
		response.Close();
	}
	catch(WebException ex)
	{
		Debug.Error("提交Apm日志失败:"+ex.Status.ToString());
		if(ex.Status.ToString().Equals("NameResolutionFailure"))//域名解释错误,重连一次,重新获取域名ip,用ip来拼接提交
		{
			ip = this.DnRetryGet("域名");
			if(ip.Equals("0"))
			{
				return
			}
			WebProxy proxy = new WebProxy(ip,80);
			this.Commit(proxy);
		}
	}
	
	if(ret.Equals("1"))
	{
		Debug.Log("提交Apm日志成功");
	}
	else
	{
		Debug.Log("提交Apm日志失败:"+ret);
	}
	
	public virtual string DnsRetryGet(string doMain)
	{
		
	}

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

(0)
上一篇 2023-12-19 17:15
下一篇 2023-12-20 13:00

相关推荐

发表回复

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

关注微信