Synchronous use of C# HttpClient
No return value function
private async void getservertime() { string servertime = "0";//Global variables are used in actual application, and the incoming parameters cannot be used for ref out keywords HttpClientHandler handler1 = new HttpClientHandler(); = false; HttpClient httpClient1 = new HttpClient(handler1); ("user-agent", UserAgent); if (InternetGetConnectedState(0, 0) == false) { //Not connected to the Internet servertime = "0"; return ; } try { HttpResponseMessage result = await ("/rest/?api="); if () { (); string responseBodyAsText = await (); JObject sertime = (responseBodyAsText); servertime=sertime["data"]["t"].ToString(); } else { servertime= "0"; } } catch (HttpRequestException hre) { servertime = "0"; ; } (); (); }
There is a return value function
private string getservertime() { HttpClientHandler handler1 = new HttpClientHandler(); = false; HttpClient httpClient1 = new HttpClient(handler1); ("user-agent", UserAgent); if (InternetGetConnectedState(0, 0) == false) { //Not connected to the Internet return "0"; } try { var task = ("/rest/?api="); (); if () (); else { return "0"; } HttpResponseMessage response = ; // = + " " + + ; var result = (); string responseBodyAsText = ; JObject sertime = (responseBodyAsText); (); (); return (sertime["data"]["t"].ToString()); } catch (HttpRequestException hre) { (); } (); (); return "0"; }
C# HttpClient docking interface
Recently, I am writing a project to connect to the DHL interface and have a general understanding of some request methods for connecting to the interface.
POST with parameters, account authentication request
HttpClient client = new HttpClient(); //Add user identity authentication = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.($"{"account"}:{"password"}"))); HttpContent httpContent = new StringContent((), Encoding.UTF8); = new MediaTypeHeaderValue("application/json"); Uri url = new Uri("Request Link"); //httpContent is the Json data carried by the requestvar msg = (url, httpContent).().Result;
Get with account authentication request
HttpClient client = new HttpClient(); //Add user identity authentication = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.($"{"account"}:{"password"}"))); Uri url = new Uri("Request Link"); var msg = (url).().Result;
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.