During project development, we often access third-party interfaces. For example, the third-party interface we need to access is the Web API. At this time, we need to use HttpHelper to call the remote interface. The HttpHelper class in the example uses Log4Net to record the request content and response content of each call, and each log is equipped with a link ID and identification, so that we can quickly find the request and response content at that time when troubleshooting problems, and then locate and analyze the problem. If you do not need to record the log when using it, just delete it.
The HttpHelper class code is as follows:
public class HttpHelper : IDisposable { private bool _disposable = false; /// <summary> /// The default utf-8 request encoding format; /// </summary> public Encoding HtmlEncoding = Encoding.UTF8; /// <summary> /// Request time /// </summary> public int Timeout = 5000; public CookieContainer Cookies = null; /// <summary> /// Whether to record cookies /// </summary> public bool IsRecordCookie = false; public string ContentType = "application/x-www-form-urlencoded"; public string AcceptLanguage = "en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3"; public string KeepAlive = "Keep-Alive"; public string Accept = "*/*"; private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"; private static ILogger Logger = (""); public HttpHelper() { //The maximum number of connections allowed is broken through the limit on concurrent connections of the Http protocol = 512; } /// <summary> /// Upload pictures /// </summary> /// <param name="url"></param> /// <param name="bArr"></param> /// <param name="fileName"></param> /// <returns></returns> public HttpRequestEntity RequestFile(string url, byte[] bArr, string fileName = "") { var result = new HttpRequestEntity { IsSuccess = 0 }; //It needs to be released later, and log collection needs to be added when enabled. //if ((url)) // throw new ArgumentNullException("Request Url cannot be null"); //if (bArr == null || <= 0) // throw new AccessViolationException("Input data is missing"); //Stream requestStream = null; //StreamReader streamReader = null; //HttpWebResponse response = null; //HttpWebRequest request = null; //try //{ // request = (url) as HttpWebRequest; // = true; // = "POST"; // string boundary = ("X"); // random divider // = "multipart/form-data;charset=utf-8;boundary=" + boundary; // byte[] itemBoundaryBytes = Encoding.("\r\n--" + boundary + "\r\n"); // byte[] endBoundaryBytes = Encoding.("\r\n--" + boundary + "--\r\n"); // if ((fileName)) // fileName = ("yyyyMMddHHmmss"); // // Request header information // StringBuilder sbHeader = new StringBuilder(("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); // byte[] postHeaderBytes = Encoding.(()); // ("auth", fileName); // Stream postStream = (); // (itemBoundaryBytes, 0, ); // (postHeaderBytes, 0, ); // (bArr, 0, ); // (endBoundaryBytes, 0, ); // (); // response = () as HttpWebResponse; // requestStream = (); // if ( == ) // { // = 0; // if (requestStream != null) // { // streamReader = new StreamReader(requestStream, HtmlEncoding); // = (); // } // } //} //catch (Exception ex) //{ // = 1; // = ; //} //finally //{ // if (requestStream != null) // { // (); // (); // } // if (streamReader != null) // { // (); // (); // } // (); // if (response != null) // (); //} return result; } /// <summary> /// Basic request method /// </summary> /// <param name="requestType">HTTP request type</param> /// <param name="url">Requested URL</param> /// <param name="requestData">Request Parameters</param> /// <param name="traceID">Link ID, convenient for querying logs</param> /// <param name="markType">Request the logo to facilitate querying the log</param> /// <returns></returns> private HttpRequestEntity BaseRequest(RequestType requestType, string url, string requestData, string traceID,string markType) { var result = new HttpRequestEntity { IsSuccess = 0 }; if ((url)) throw new ArgumentNullException("Requested Url cannot be null"); Stopwatch stopwatch = new Stopwatch(); (); Dictionary<string, object> resultLog = new Dictionary<string, object>();//log object ("logType", "remote"); ("traceID", traceID); ("localIp", ); ("markType", markType); ("url", url); ("requestContent", (requestData, Encoding.UTF8)); ("createTime", ("yyyy-MM-dd HH:mm:")); StackTrace ss = new StackTrace(true); mb = (2).GetMethod();//0 represents the current stack space, 1 represents the previous level stack space, and so on in turn ("className", ); ("methodName", ); HttpStatusCode statusCode = ; if (IsRecordCookie) Cookies = new CookieContainer(); Stream requestStream = null; StreamReader streamReader = null; HttpWebRequest webRe = null; HttpWebResponse webPos = null; try { if (("https", )) { = new RemoteCertificateValidationCallback(CheckValidationResult); webRe = (url) as HttpWebRequest; = HttpVersion.Version10; } else { webRe = (HttpWebRequest)(url); } ("Accept-Language", AcceptLanguage); ("Keep-Alive", KeepAlive); = UserAgent; = Accept; = Timeout; = Timeout; = Cookies; if (requestType == ) { = ("{0}; {1}", ContentType, ); byte[] datas = (requestData); = "POST"; = ; = -1; requestStream = (); (datas, 0, ); (); (); } else = "GET"; webPos = (HttpWebResponse)(); ("requestType", ); statusCode = ; = ; = ; requestStream = (); if ( == ) { = 0; if (requestStream != null) { streamReader = new StreamReader(requestStream, HtmlEncoding); = (); } } } catch (Exception ex) { = 1; = ; } finally { if (requestStream != null) { (); (); } if (streamReader != null) { (); (); } (); if (webPos != null) (); } if ( == 1) { ("status", ); ("success", false); ("responseContent", ); (); ("elapseTime", ); string log = (resultLog); (log); (log); } else { ("status", statusCode); ("success", true); ("responseContent", ); (); ("elapseTime", ); string log = (resultLog); (log); } return result; } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //Always accept } /// <summary> /// Get request /// </summary> /// <param name="url">Request address</param> /// <param name="traceID">Link ID, convenient for querying logs</param> /// <param name="markType">Request the logo to facilitate querying the log</param> /// <returns></returns> public HttpRequestEntity Request(string url, string traceID, string markType) { return BaseRequest(, url, , traceID, markType); } /// <summary> /// Post request /// </summary> /// <param name="url">Request address Url</param> /// <param name="requestData">Request content parameters</param> /// <param name="traceID">Link ID, convenient for querying logs</param> /// <param name="markType">Request the logo to facilitate querying the log</param> /// <returns></returns> public HttpRequestEntity Request(string url, string requestData, string traceID, string markType) { return BaseRequest(, url, requestData, traceID, markType); } ~HttpHelper() { Dispose(false); } #region IDisposable Member public void Dispose() { Dispose(true); (this); } protected virtual void Dispose(bool disposing) { if (this._disposable) return; if (disposing) { } _disposable = true; } #endregion } /// <summary> /// HttpHelper request method /// </summary> public enum RequestType { /// <summary> /// Get request /// </summary> Get, /// <summary> /// Post request /// </summary> Post } /// <summary> /// Return entity when HttpHelper request /// </summary> public class HttpRequestEntity { /// <summary> /// Whether the request is successful 0-Success (return to Http status code 200) 1-Failed (exception occurred) /// </summary> public int IsSuccess { get; set; } /// <summary> /// Request to return content /// </summary> public string ResponseContent { get; set; } /// <summary> /// Request to return content length /// </summary> public long ResponseLength { get; set; } /// <summary> /// Request to return the encoding type /// </summary> public string ResponseEncodingName { get; set; } }
The call example is as follows:
HttpHelper helper = new HttpHelper(); HttpRequestEntity response = ("The URL to access", "Request the required parameters", "Access Link ID", "Access Identification"); if ( != 0) { //The program handles exception, please try again!} else { //The request response is successful}
This is the article about the detailed explanation of the examples of C# implementing HTTP access class HttpHelper. For more related contents of C# HTTP access class HttpHelper, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!