HttpClient测试
using System
.Collections
.Generic
;
using System
.IO
;
using System
.Net
.Http
;
using System
.Net
.Http
.Headers
;
using System
.Windows
;
namespace WpfHttpClient
{
public partial class MainWindow : Window
{
private readonly IHttpClientFactory _httpClientFactory
;
HttpClient client
;
public MainWindow(IHttpClientFactory httpClientFactory
)
{
InitializeComponent();
_httpClientFactory
= httpClientFactory
;
client
= _httpClientFactory
.CreateClient();
}
private async void ButtonGET_Click(object sender
, RoutedEventArgs e
)
{
string html_get_content
= await client
.GetStringAsync("http://httpbin.org/get");
ShowInfo(html_get_content
);
}
private async void ButtonPost1_Click(object sender
, RoutedEventArgs e
)
{
MultipartFormDataContent content
= new MultipartFormDataContent();
content
.Headers
.Add("UserName", "admin");
content
.Headers
.Add("Password", "123");
using (Stream stream
= File
.OpenRead(@"oldMan.jpg"))
{
content
.Add(new StreamContent(stream
), "oldMan", "oldMan.jpg");
var respMsg
= await client
.PostAsync("http://httpbin.org/post", content
);
string html_post_content
= await respMsg
.Content
.ReadAsStringAsync();
ShowInfo(html_post_content
);
}
}
private async void ButtonPost2_Click(object sender
, RoutedEventArgs e
)
{
string json
= "{userName:'admin',password:'123'}";
StringContent content
= new StringContent(json
);
content
.Headers
.ContentType
= MediaTypeHeaderValue
.Parse("application/json");
var respMsg
= await client
.PostAsync("http://httpbin.org/post", content
);
string html_post_content
= await respMsg
.Content
.ReadAsStringAsync();
ShowInfo(html_post_content
);
}
private async void ButtonPost3_Click(object sender
, RoutedEventArgs e
)
{
Dictionary
<string, string> nameValues
= new Dictionary<string, string>();
nameValues
["userName"] = "admin";
nameValues
["password"] = "8888888";
FormUrlEncodedContent content
= new FormUrlEncodedContent(nameValues
);
content
.Headers
.ContentType
= MediaTypeHeaderValue
.Parse("application/json");
var respMsg
= await client
.PostAsync("http://httpbin.org/post", content
);
string html_post_content
= await respMsg
.Content
.ReadAsStringAsync();
ShowInfo(html_post_content
);
}
private void ShowInfo(string msg
)
{
this.txtInfo
.Text
= msg
;
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-7905.html