创建Http类请求类型的封装
设置请求类型
public enum HttpType
{
GET,
POST,
PUT,
DELETE,
HeAD,
}
发送请求的方法 返回字符串类型
<param name="URL">请求地址</param>
<param name="type">请求类型,默认值是GET</param>
<param name="data">请求数据</param>
<param name="isJson">请求内容类型</param>
设置请求体内容类型
如果isJson== true 证明传递数据是JSON格式 设置请求内容类型为application/json.
如果isJson==false 证明传递数据不是JSON格式 设置请求体内容类型为application/x-www-from-urlencoded
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)
{
request.ContentType = isJson ? "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);
});
}
同步请求
同步GET
private void button1_Click(object sender, EventArgs e)
{
string s = Http.Send("http://192.168.113.74:3000/All");
string s1 = Http.Send("http://192.168.113.74:3000/getTest?type=2");
Console.WriteLine(s);
this.label1.Text = s1;
}
同步post 字符串拼接
private void button2_Click(object sender, EventArgs e)
{
string s = Http.Send("http://192.168.113.74:3000/register", Http.HttpType.POST,"name=小玲&psw=1236796966",false);
this.label1.Text = s;
}
同步post2 JSON格式
private void button3_Click(object sender, EventArgs e)
{
string s = Http.Send("http://192.168.113.74:3000/register", Http.HttpType.POST, "{\"name\":\"阿玲\",\"psw\":123456}",true);
this.label1.Text = s;
}
异步
异步GET
private async void button6_Click(object sender, EventArgs e)
{
string s = await Http.SendAsync("http://192.168.113.74:3000/login?name=10001&psw=123456");
this.label1.Text= s;
}
异步post1 字符拼接
private async void button5_Click(object sender, EventArgs e)
{
string s = await Http.SendAsync("http://192.168.113.74:3000/register", Http.HttpType.POST, "name=艮奴盖地虎&psw=12345678", false);
this.label1.Text = s;
}
异步post2 JSON格式
private async void button4_Click(object sender, EventArgs e)
{
string s = await Http.SendAsync("http://192.168.113.74:3000/register", Http.HttpType.POST,"{\"name\":\"叮铃\",\"psw\":123456}",true);
this.label1.Text = s;
}