C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# HttpClient同步使用

C#之HttpClient的同步使用方式

作者:cnwjl

这篇文章主要介绍了C#之HttpClient的同步使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

C# HttpClient的同步使用

无返回值 函数

  private async void  getservertime()
        {
            string servertime = "0";//实际应用时用全局变量 ,传入参数不可用ref out关键字
            HttpClientHandler handler1 = new HttpClientHandler();
            handler1.AllowAutoRedirect = false;
            HttpClient httpClient1 = new HttpClient(handler1);
            httpClient1.DefaultRequestHeaders.Add("user-agent", UserAgent);
            if (InternetGetConnectedState(0, 0) == false)
            {
                //未联网
                servertime = "0";
                return ;
            }
             
            try
            {
                HttpResponseMessage  result  = await  httpClient1.GetAsync("https://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
               
                if (result.IsSuccessStatusCode)
                {
                    result.EnsureSuccessStatusCode();
                    string responseBodyAsText = await result.Content.ReadAsStringAsync();
                    JObject sertime = JObject.Parse(responseBodyAsText);                  
                    servertime=sertime["data"]["t"].ToString();                 
                }
                    
                else
                {
                    servertime= "0";
                }
               
 
            }
            catch (HttpRequestException hre)
            {
                servertime = "0"; ;
            }
            handler1.Dispose();
            httpClient1.Dispose();
 
 
        }

有返回值函数

    private string getservertime()
 
        {
            HttpClientHandler handler1 = new HttpClientHandler();
           
            handler1.AllowAutoRedirect = false;
            HttpClient httpClient1 = new HttpClient(handler1);
            httpClient1.DefaultRequestHeaders.Add("user-agent", UserAgent);
            if (InternetGetConnectedState(0, 0) == false)
            {
              //未联网
                return "0";
            }
             
            try
            {
                var task = httpClient1.GetAsync("https://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
                task.Wait();
                if (task.Result.IsSuccessStatusCode)
                    task.Result.EnsureSuccessStatusCode();
                else
                {
                    return "0";
                }
                HttpResponseMessage response = task.Result;
 
                //  txtStatusCode.Text = response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine;
 
                var result = response.Content.ReadAsStringAsync();
                string responseBodyAsText = result.Result;
 
                JObject sertime = JObject.Parse(responseBodyAsText);
                handler1.Dispose();
                httpClient1.Dispose();
                return (sertime["data"]["t"].ToString());
 
 
            }
            catch (HttpRequestException hre)
            {
                hre.ToString();
            }
            handler1.Dispose();
            httpClient1.Dispose();
            return "0";
 
          
        }

C# HttpClient对接接口

最近在写对接DHL接口的项目,大致了解了一些对接接口的请求方法。

POST带参数,账号认证请求

HttpClient client = new HttpClient();
//添加用户身份认证
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{"账号"}:{"密码"}")));

HttpContent httpContent = new StringContent(stringBuilder.ToString(), Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Uri url = new Uri("请求链接");
//httpContent为请求携带的Json数据
var msg = client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;

Get带账号认证请求

 HttpClient client = new HttpClient();
 //添加用户身份认证
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{"账号"}:{"密码"}")));
 
Uri url = new Uri("请求链接");
var msg = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文