/// <summary> /// 超时回调 /// </summary> /// <param name="state">HttpRequest对象</param> /// <param name="timedOut">超时判断</param> void TimeoutCallback(object state, bool timedOut) { AsyncHttpItem pa = state as AsyncHttpItem; if (timedOut) { if (System.Threading.Interlocked.Increment(ref pa.atomLock) == 1) { pa.result.Html = "TimeOut"; pa.callBack.Invoke(pa.result); } } }
/// <summary> /// 根据传入的参数,来异步发起请求 /// </summary> /// <param name="objItems">请求设置参数</param> /// <param name="callBack">回调函数</param> private void AsyncGetHttpRequestData(HttpItems objItems, Action <HttpResults> callBack) { AsyncHttpItem hrt = new AsyncHttpItem(); SetRequest(objItems); hrt.objHttpCodeItem = objItems; hrt.request = request; hrt.callBack = callBack; try { IAsyncResult m_ar = hrt.request.BeginGetResponse(AsyncResponseData, hrt); System.Threading.ThreadPool.RegisterWaitForSingleObject(m_ar.AsyncWaitHandle, TimeoutCallback, hrt, objItems.Timeout, true); } catch { hrt.result.Html = "TimeOut"; } }
/// <summary> /// 异步获取响应数据 /// </summary> /// <param name="result"></param> private void AsyncResponseData(IAsyncResult result) { AsyncHttpItem hrt = result.AsyncState as AsyncHttpItem; if (System.Threading.Interlocked.Increment(ref hrt.atomLock) != 1) { return; } try { request = hrt.request; //response = (HttpWebResponse)hrt.request.EndGetResponse(result); response = (HttpWebResponse)request.EndGetResponse(result); hrt.result = GetResponesInfo(ref hrt.objHttpCodeItem); hrt.result.Cookie = new XJHTTP().UpdateCookie(hrt.objHttpCodeItem.Cookie, hrt.result.Cookie); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; hrt.result.Html = ex.Message; if (response != null) { hrt.result.StatusCode = response.StatusCode; hrt.result.StatusDescription = ex.Message; try { hrt.result = GetResponesInfo(ref hrt.objHttpCodeItem); } catch { } } else { hrt.result.StatusCode = HttpStatusCode.NotFound; hrt.result.StatusDescription = ex.Message; } } hrt.callBack.Invoke(hrt.result); }