zoukankan      html  css  js  c++  java
  • .NET处理HTTP请求

    第一种:使用HttpWebRequest

    string result = "";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);
                request.Method = "POST";
                request.ContentType = "application/json";
                string data = "{
    "header": {
    "token": "30xxx6aaxxx93ac8cxx8668xx39xxxx",
    "username": "jdads",
    "password": "liuqiangdong2010",
    "action": ""
    },
    "body": {}
    }";
                data = jsonData;
                byte[] byteData = Encoding.UTF8.GetBytes(data.ToString());
                request.ContentLength = byteData.Length;
    
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }
                try
                {
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        result = reader.ReadToEnd();
                        Console.WriteLine(result);
    
                    }
                }
                


    第二种:WebClient,也过时了:
    第三种:HttpClient 当前主流用法,异步请求,自.NET4.5开始可从Nuget包管理中获取。

     static async Task<Product> GetProductAsync(string path)
            {
                Product product = null;
                HttpResponseMessage response = await client.GetAsync(path);
                if (response.IsSuccessStatusCode)
                {
                    product = await response.Content.ReadAsAsync<Product>();
                }
                return product;
            }

    第四种:第三方类库:

    RestSharp

    REST API请求测试类库,可通过 NuGet 获得。

    Flurl.Http

    最新的便捷的api测试工具,使用HttpClient实现,可通过 NuGet 安装。

    参考

    Call a Web API From a .NET Client (C#)

  • 相关阅读:
    Python 编码格式的使用
    解决cmd 运行python socket怎么终止运行
    解决win10子系统Ubuntu新装的mysql 不能root登陆方法
    浏览器中网址访问过程详解
    POJ 2502 最短路
    HDU 2859
    POJ 3186
    POJ 1661 暴力dp
    POJ 1015 陪审团问题
    CodeForces 1058E
  • 原文地址:https://www.cnblogs.com/xinyf/p/10045577.html
Copyright © 2011-2022 走看看