请求封装
在我们使用请求的使用避免不了多次请求,这样代码的重复率就会变高,我们可以将请求进行封装进而调用,不仅提高了代码的重用性也提高了代码的质量
封装
internal class Http
{
/// <summary>
/// 请求类型
/// </summary>
public enum HttpType
{
GET,
POST,
PUT,
DELETE,
HEAD,
}
/// <summary>
/// 发送请求的方法 返回字符串类型
/// URL 请求地址
/// type: 请求类型 默认值是GET
/// </summary>
/// <param name="url">请求地址</pramas>
/// <param name="type">请求类型,默认值是GET</pramas>
/// <param name="data">请求数据</param>
/// <param name="isjson">请求内容类型</param>
/// <returns>字符串类型</returns>
public static string Send(string url,HttpType type = HttpType.GET,string data = "",bool isjson = false)
{
WebRequest request = WebRequest.Create(url);
request.Method = type.ToString();
if (type == HttpType.POST || type == HttpType.PUT)
{
// 设置请求体内容类型
// 如果isJson == true 证明传递数据是json格式 设置请求体从内容类型为application/json
// 如果isJson == false 证明传递数据不是json格式 设置请求体内容类型为application/x-www-form-urlencoded
request.ContentType = isjson ==true? "application/json" : "application/x-www-form-urlencoded";
Stream s = request.GetRequestStream(); // 获取请求数据流
byte[] bs = Encoding.UTF8.GetBytes(data); // 把data转成字节数组
s.Write(bs,0,bs.Length); // 请求流添加数据
}
WebResponse response = request.GetResponse();
Stream res = response.GetResponseStream(); // 响应数据流
StreamReader sr = new StreamReader(res);
string resData = sr.ReadToEnd();
return resData;
}
// 异步的请求
public static Task<string> SendAsync(string url, HttpType type = HttpType.GET, string data = "", bool isjson = false)
{
return Task.Run(() =>
{
return Send(url,type,data,isjson);
});
}
}
使用
Console.WriteLine("=======================异步POST JSON格式===================");
string s= await Http.SendAsync("http://192.168.113.74:3000/register", Http.HttpType.POST, "{\"name\":\"呕吐曼\",\"psw\":\"123456\"}", true);
Console.WriteLine(s);
标签:封装,请求,GET,data,HttpType,HTTP,type,string
From: https://blog.csdn.net/qq_3517289697/article/details/140495491