RestSharp简单的HTTP请求辅助类

在.net中,using System.Net包可以使用HttpWebRequest发起一个HTTP请求:

            var posturl="http://localhost:8088/api/test";
            var req = HttpWebRequest.Create(posturl);
            req.Headers.Add("head", headData);
            req.Method = "POST";
            req.Timeout = 60000;
            var bodyBytes = Encoding.UTF8.GetBytes(bodyData);
            req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
            var resp = req.GetResponse();
            var streamReader = new StreamReader(resp.GetResponseStream());
            string result = streamReader.ReadToEnd();
            resp.Close();
            streamReader.Close();
            req.Abort();
            return result;

这是使用.net原生的方法。这里需要处理流,还得关闭它们。而RestSharp封装好了这些东东,简洁易用,还能自主反序列化请求结果。下面来看看使用RestSharp后的代码:

var posturl="http://localhost:8088/api/test";
  RestClient client = new RestClient(posturl);
            client.Timeout = 60000;
            RestRequest request = new RestRequest(Method.POST);
            request.AddHeader("head", headData);
            request.AddParameter("body", encryptBody);
            string result = client.Execute(request).Content;
             return result;

明显省去了一半代码,这里还能反序列化:

string resultObj = client.Execute(request);
RespMsg respMsg =resultObj.Data;

你可能感兴趣的:(.net,编程开发技巧,系统架构,后端开发)