zoukankan      html  css  js  c++  java
  • 网络编程采用HttpClient类更好

    一般人网络编程普遍用HttpWebRequest,类似下面的实现。我也一般都这样实现

     string result = string.Empty;
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(requesturl));
                    request.Method = method; 
                    request.ContentType = "application/json";
                    request.Headers["Authorization"] = AuthStr;
                    if (!string.IsNullOrWhiteSpace(jsonstr))
                    {
                        using (var requestStream = await request.GetRequestStreamAsync())
                        {
                            var writer = new StreamWriter(requestStream);
                            writer.Write(jsonstr);
                            writer.Flush();
                        }
                    }
                    using (var resp = await request.GetResponseAsync())
                    {
                        using (var responseStream = resp.GetResponseStream())
                        {
                            var reader = new StreamReader(responseStream);
                            result = reader.ReadToEnd();
                        }
                    }
                    return result;
    

      但微软建议采用System.Net.Http.HttpClient类:MSDN链接

    使用HttpClient类的确是比较简洁了。

     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer",AuthStr);
                    HttpContent content = new StringContent(jsonstr,Encoding.UTF8);
                    content.Headers.ContentType.CharSet = null;
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    System.Net.Http.HttpResponseMessage response = await client.PutAsync(new Uri(requesturl), content);
                    response.EnsureSuccessStatusCode();
                    string responseBody = System.Text.RegularExpressions.Regex.Unescape(await response.Content.ReadAsStringAsync());
                    return responseBody;
  • 相关阅读:
    4.iptables 网络防火墙
    iterator not dereferencable问题
    秒杀多线程系列中的题目
    说说僵尸和孤儿进程的那点儿事
    Linux的fork()写时复制原则(转)
    linux进程原语之fork()
    linux--多进程进行文件拷贝
    哈夫曼树与哈夫曼编码
    csp公共钥匙盒
    字典树
  • 原文地址:https://www.cnblogs.com/ssvip/p/11761244.html
Copyright © 2011-2022 走看看