This article briefly introduces the Http request in C#. I helped my friend’s project encapsulate ApiHelper a few days ago. My rough results are as follows. Think about it, I am really far from it. There is also an architect who is also encapsulating this Helper, so the final result is of course to use Daniu's packaging. After this article, I will learn about his ideas such as packaging, configuration, error handling mechanism, etc. However, this time I also learned more about C# network programming, which is a learning experience. I really like to work with the veteran driver. In the next stage, I will continue to learn the underlying packaging of the project with this friend and his modest attitude. It is also lucky to have such an opportunity.
You can encapsulate it into your own HttpHelper, and as suggested by a friend, unify the incoming and outgoing parameters of Http requests. In terms of HttpClient, we also refer to dudu's article on httppclient warm-up.Notes on using HttpClient in C#: Preheat and long connection。
In order to achieve unified incoming and outgoing parameters, Req<T> generic classes and Resp<T> generic classes are defined. You can expand according to your needs.
public class Req<T> { /// <summary> /// Incoming data /// </summary> public T Input { get; set; } /// <summary> /// Request address /// </summary> public string Url { get; set; } }
public class Resp<T> { /// <summary> /// Error message /// </summary> public string ErrorMsg { get; set; } /// <summary> /// Status code /// </summary> public int StatusCode { get; set; } /// <summary> /// Return data /// </summary> public T RespData { get; set; } }
Although the httpClient object reuse is maintained, it should be noted that after setting httpClient and a request occurs, its properties cannot be reset. This is also the reason why I defined a fileClient again.
#region HttpClient Version private static readonly string _baseAddress = ["api-server"];//Configure BaseUrl://localhost:1234 private static readonly HttpClient _httpClient; private static readonly HttpClient _fileClient; static ApiHelper() { #region Initialization and warm-up httpClient _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri(_baseAddress); _httpClient.Timeout = (2000); _httpClient.("Accept", "application/json");//application/xml data format that wants Accept _httpClient.SendAsync(new HttpRequestMessage { Method = new HttpMethod("HEAD"), RequestUri = new Uri(_baseAddress + "/api/test/HttpClientHot") }) .(); #endregion #region Initialization and warm-up fileClient _fileClient = new HttpClient(); _fileClient.BaseAddress = new Uri(_baseAddress + "/api/test/HttpClientHot"); _fileClient.MaxResponseContentBufferSize = 256000; #endregion } /// <summary> /// http Get request /// </summary> /// <typeparam name="T">Input parameter type</typeparam> /// <typeparam name="TResult">Export parameter type</typeparam> /// <param name="req">Input parameter object</param> /// <returns></returns> public static async Task<Resp<TResult>> GetAsync<T, TResult>(Req<T> req) { try var result =await _httpClient.GetAsync().(); return new Resp<TResult>() { Data = <TResult>(result) }; } catch(Exception ex) } return new Resp<TResult>() { Data = <TResult>("") }; } /// <summary> /// http Post request /// </summary> /// <typeparam name="T">Input parameter type</typeparam> /// <typeparam name="TResult">Export parameter type</typeparam> /// <param name="req">Input parameter object</param> /// <returns></returns> public static async Task<Resp<TResult>> PostAsJsonAsync<T, TResult>(Req<T> req) var result = await _httpClient.PostAsJsonAsync(, ).(); return new Resp<TResult>() { Data = <TResult>(result) }; } /// Upload file /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="req"></param> /// <param name="filePath"></param> public static async Task<Resp<TResult>> SendFile<T, TResult>(Req<T> req, string filePath)//D:\\ //_fileClient.("user-agent", "User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");//Set the request header // Read file stream FileStream fs = new FileStream(filePath, , , ); HttpContent fileContent = new StreamContent(fs);// HTTP container provided for file stream = ("multipart/form-data");//Set media type MultipartFormDataContent mulContent = new MultipartFormDataContent("----");//Create a container for passing files string fileName = (("/") + 1); (fileContent, "form", fileName);//The second parameter is the form name and the third is the file name. HttpResponseMessage response = await _fileClient.PostAsync(, mulContent); (); string result = await (); return new Resp<TResult>() { Data = <TResult>(result) }; } /// download /// <param name="url"></param> /// <returns></returns> public static async Task<Resp<byte[]>> HttpDownloadData<T>(Req<T> req) var byteres = await _fileClient.GetByteArrayAsync(); return new Resp<byte[]>() { Data = byteres }; #endregion }
Also share the requests implemented by HttpWebRequest. HttpWebRequest requires you to set a lot of content by yourself, and of course this also proves that it is rich in content. The following code includes post, get, and upload.
/// <summary> /// Post Http request /// </summary> /// <param name="url">Request address</param> /// <param name="postData">Transfer data</param> /// <param name="timeout">Timeout</param> /// <param name="contentType">Media format</param> /// <param name="encode">Encoding</param> /// <returns>Generic Collection</returns> public static List<T> PostAndRespList<T>(string url, string postData, int timeout = 5000, string contentType = "application/json;", string encode = "UTF-8") { if (!(url) && !(encode) && !(contentType) && postData != null) { // ("Authorization", "Bearer " + "SportApiAuthData"); HttpWebResponse webResponse = null; Stream responseStream = null; Stream requestStream = null; StreamReader streamReader = null; try { string respstr = GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType); return <List<T>>(respstr); } catch (Exception ex) { } finally { if (responseStream != null) (); if (webResponse != null) (); if (requestStream != null) (); if (streamReader != null) (); } } return null; } /// <summary> /// Post Http request /// </summary> /// <param name="url">Request address</param> /// <param name="postData">Transfer data</param> /// <param name="timeout">Timeout</param> /// <param name="contentType">Media format</param> /// <param name="encode">Encoding</param> /// <returns>Generic Collection</returns> public static T PostAndRespSignle<T>(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8") { if (!(url) && !(encode) && !(contentType) && postData != null) { // ("Authorization", "Bearer " + "SportApiAuthData"); HttpWebResponse webResponse = null; Stream responseStream = null; Stream requestStream = null; StreamReader streamReader = null; try { string respstr = GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType); return <T>(respstr); } catch (Exception ex) { } finally { if (responseStream != null) (); if (webResponse != null) (); if (requestStream != null) (); if (streamReader != null) (); } } return default(T); } /// <summary> /// Post Http request /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <param name="timeout"></param> /// <param name="contentType"></param> /// <param name="encode"></param> /// <returns>Response Stream String</returns> public static string PostAndRespStr(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8") { if (!(url) && !(encode) && !(contentType) && postData != null) { HttpWebResponse webResponse = null; Stream responseStream = null; Stream requestStream = null; StreamReader streamReader = null; try { return GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType); } catch (Exception ex) { } finally { if (responseStream != null) (); if (webResponse != null) (); if (requestStream != null) (); if (streamReader != null) (); } } return null; } private static string GetStreamReader(string url, Stream responseStream, Stream requestStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode, string postData, string contentType) { byte[] data = (encode).GetBytes(postData); HttpWebRequest webRequest = (HttpWebRequest)(url); SetAuth(webRequest); = "POST"; = contentType + ";" + encode; = ; = timeout; requestStream = (); (data, 0, ); webResponse = (HttpWebResponse)(); responseStream = (); if (responseStream == null) { return ""; } streamReader = new StreamReader(responseStream, (encode)); return (); } /// <summary> /// Stream the Post file to the specified URL /// </summary> /// <param name="url">url</param> /// <param name="filePath">File Path</param> /// <returns>Response Stream String</returns> public static string PostFile(string url, string filePath, string contentType = "application/octet-stream", string encode = "UTF-8") { if (!(url) && !(encode) && !(contentType) && !(filePath)) { Stream requestStream = null; Stream responseStream = null; StreamReader streamReader = null; FileStream fileStream = null; try { // Set parameters HttpWebRequest webRequest = (url) as HttpWebRequest; SetAuth(webRequest); = true; = "POST"; string boundary = ("X"); // Random divider = "multipart/form-data;charset=" + encode + ";boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.("\r\n--" + boundary + "\r\n");//The message begins byte[] endBoundaryBytes = Encoding.("\r\n--" + boundary + "--\r\n");//End of message var fileName = (("/") + 1); //Request header information string postHeader = ("Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:{1}\r\n\r\n", fileName, contentType); byte[] postHeaderBytes = Encoding.(postHeader); fileStream = new FileStream(filePath, , ); byte[] fileByteArr = new byte[]; (fileByteArr, 0, ); (); requestStream = (); (itemBoundaryBytes, 0, ); (postHeaderBytes, 0, ); (fileByteArr, 0, ); (endBoundaryBytes, 0, ); (); responseStream = ().GetResponseStream();//Send a request and get the response flow if (responseStream == null) return ; streamReader = new StreamReader(responseStream, Encoding.UTF8); return (); } catch (Exception ex) { } finally { } } return null; } /// <summary> /// Get http request /// </summary> /// <param name="url">Request address</param> /// <param name="timeout">Timeout</param> /// <param name="encode">Encoding</param> /// <returns>Returns a single entity</returns> public static T GetSingle<T>(string url, int timeout = 5000, string encode = "UTF-8") { //HttpWebRequest object //HttpClient->dudu call preheating //Stream—>Model if (!(url) && !(encode)) { Stream responseStream = null; StreamReader streamReader = null; WebResponse webResponse = null; try { string respStr = GetRespStr(url, responseStream, streamReader, webResponse, timeout, encode); return <T>(respStr); } catch (Exception ex) { } finally { if (responseStream != null) (); if (streamReader != null) (); if (webResponse != null) (); } } return default(T); } /// <summary> /// Get http request /// </summary> /// <param name="url"></param> /// <param name="timeout"></param> /// <param name="encode"></param> /// <returns>Response Stream String</returns> public static string GetResponseString(string url, int timeout = 5000, string encode = "UTF-8") { if (!(url) && !(encode)) { Stream responseStream = null; StreamReader streamReader = null; WebResponse webResponse = null; try { return GetRespStr(url, responseStream, streamReader, webResponse, timeout, encode); } catch (Exception ex) { } finally { if (responseStream != null) (); if (streamReader != null) (); if (webResponse != null) (); } } return null; } private static string GetRespStr(string url, Stream responseStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode) { HttpWebRequest webRequest = (HttpWebRequest)(url); = "GET"; = timeout; webResponse = (); responseStream = (); if (responseStream == null) { return ""; } streamReader = new StreamReader(responseStream, (encode)); return (); }
This is the end of this article about Http requests in C# network programming. For more related contents of Http requests in C# network programming, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!