• .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#)

  • 相关阅读:
    Scrum立会报告+燃尽图 01
    robotframework笔记6
    robotframework笔记7
    robotframework笔记5
    loadrunner函数
    robotframework笔记4
    robotframework笔记3--如何编写好的测试用例使用机器人的框架
    robotframework笔记2
    robotframework笔记1
    eclipes的Spring注解SequenceGenerator(name="sequenceGenerator")报错的解决方式
  • 原文地址:https://www.cnblogs.com/xinyf/p/10045577.html
Copyright © 2020-2023  润新知