You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB
C#

1 year ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
namespace HttpClientStudy.UnitTest
{
public class HttpClientTest
{
private readonly ITestOutputHelper _logger;
public HttpClientTest(ITestOutputHelper outputHelper)
{
_logger = outputHelper;
}
1 year ago
#region Get请求中使用请求体强烈不推荐这种方法
1 year ago
/// <summary>
/// Get请求中使用请求体
/// 注意:服务器要设置(配置KestrelServerOptions AllowSynchronousIO值为true)
/// </summary>
/// <returns></returns>
[Fact]
1 year ago
public async Task GetWithBody_Test()
1 year ago
{
HttpClient httpClient = new HttpClient();
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2")
};
1 year ago
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get,"http://localhost:5189/api/AdvancedGet/GetWithBody");
1 year ago
requestMessage.Content = new FormUrlEncodedContent(formData);
var response = await httpClient.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
1 year ago
var responseText = await response.Content.ReadAsStringAsync();
_logger.WriteLine(responseText);
1 year ago
}
1 year ago
/// <summary>
/// Post模型绑定对比
/// </summary>
/// <returns></returns>
[Fact]
public async Task PostDemo_Test()
{
HttpClient httpClient = new HttpClient();
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1", "value1"),
new KeyValuePair<string, string>("param2", "value2")
};
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5189/api/AdvancedGet/PostDemo");
requestMessage.Content = new FormUrlEncodedContent(formData);
var response = await httpClient.SendAsync(requestMessage);
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
_logger.WriteLine(responseText);
}
#endregion
1 year ago
}
}