C#客户端HttpClient请求认证及数据传输
⽬录
⼀,授权认证
1. 基础认证⽰例
2. JWT 认证⽰例
3. Cookie ⽰例
⼆,请求类型
三,数据传输
1. Query
2. Header
3. 表单
4. JSON
5. 上传⽂件
⼀,授权认证
客户端请求服务器时,需要通过授权认证许可,⽅能获取服务器资源,⽬前⽐较常见的认证⽅式有 Basic 、JWT、Cookie。HttpClient 是 C# 中的 HTTP/HTTPS 客户端,⽤于发送 HTTP 请求和接收来⾃通过 URI 确认的资源的 HTTP 响应。下⾯以具体代码做⽰范。
1. 基础认证⽰例
// Basic基础认证
public async Task Basic(string user, string password, string url)
{
// 如果认证页⾯是 https 的,请参考⼀下 jwt 认证的 HttpClientHandler
// 创建 client
HttpClient client = new HttpClient();
// 创建⾝份认证
// using System.Net.Http.Headers;
AuthenticationHeaderValue authentication = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")
));
client.DefaultRequestHeaders.Authorization = authentication;
byte[] response = await client.GetByteArrayAsync(url);
client.Dispose();
}
可以看到 Basic 认证的安全程度⾮常低,多⽤于路由器和嵌⼊式设备,⽽且往往不会使⽤ HTTPS。
2. JWT 认证⽰例
// Jwt认证
public async Task Bearer(string token, string url)
{
// HttpClientHandler及其派⽣类使开发⼈员能够配置各种选项, 包括从代理到⾝份验证。
// helpLink docs.microsoft/en-us/dotnet/api/system.http.httpclienthandler?view=netframework-4.8
var httpclientHandler = new HttpClientHandler();
// 如果服务器有 https 证书,但是证书不安全,则需要使⽤下⾯语句
// => 也就是说,不校验证书,直接允许
httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
using (var httpClient = new HttpClient(httpclientHandler))
{
// 创建⾝份认证
// System.Net.Http.Headers.AuthenticationHeaderValue;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
await httpClient.GetAsync(url);
httpClient.Dispose();
}
}
JWT 认证,需要客户端携带 token ,token 是⼀段加密过的字符串,关于原理这⾥不多说,token 是通过客户端 header 携带的。另外,对于测试的 Web 应⽤或者内⽹应⽤, HTTPS 证书可能不是公⽹国际认证的证书,就需要跳过认证,直接允许访问使⽤。
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
};
3. Cookie ⽰例
HttpClient 中,Cookie 有两种处理⽅式。
⼀种是已经知道 Cookie ,直接将 Cookie 存储到 HttpClient 中;另⼀种是还没有 Cookie ,通过账号密码登录获取到 Cookie ,⾃动存储到 HttpClient 对象中,接着使⽤当前 HttpClient 对象请求 URL。
两种⽅式的设定,是通过 HttpClientHandler 的 UseCookies 属性设置的。
⽰例
var httpclientHandler = new HttpClientHandler()
{
UseCookies = true
};
UseCookies 获取或设置⼀个值,该值指⽰处理程序是否使⽤ CookieContainer 属性存储服务器 Cookie,并在发送请求时使⽤这些 Cookie。
⽅式1:
// 先⽤账号密码登陆再请求
public async Task Cookie(string user, string password, string loginUrl, string url)
{
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
UseCookies = true
};
// 如果服务器有 https 证书,但是证书不安全,则需要使⽤下⾯语句
// => 也就是说,不校验证书,直接允许
var loginContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("user",user),
new KeyValuePair<string, string>("password",password)
});
using (var httpClient = new HttpClient(httpclientHandler))
{
// 先登陆
var result = await httpClient.PostAsync(loginUrl, loginContent);
// 登陆成功后,客户端会⾃动携带 cookie ,不需要再⼿动添加
//if (result.IsSuccessStatusCode)
//{
// /*
// * 如果请求成功
// */
//}
var result2 = await httpClient.GetAsync(url);
// httpclient 已经携带 Cookie ,可以多次使⽤
// var result3 = await httpClient.GetAsync(url3);
/
/ var result4 = await httpClient.GetAsync(url4);
httpClient.Dispose();
}
}
⽅式2:
//已经拿到 cookie ,直接使⽤ cookie 请求
public async Task Cookie(string cookie, string url)
{
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
UseCookies = false
};
// 如果服务器有 https 证书,但是证书不安全,则需要使⽤下⾯语句
// => 也就是说,不校验证书,直接允许
using (var httpClient = new HttpClient(httpclientHandler))
{
httpClient.DefaultRequestHeaders.Add("Cookie", cookie);
await httpClient.GetAsync(url);
httpClient.Dispose();
}
}
⼆,请求类型
HTTP 请求⾥,有 GET、POST、DELETE、PUT 等请求⽅式。
HttpClient 中,有以下请求相关的⽅法
CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
error parse newPostAsync
PutAsync
SendAsync
其中, CancelPendingRequests 是取消该实例所有挂起的请求,不是请求类型。SendAsync ⽤于处理送 HttpRequestMessage(表⽰⼀条 HTTP 请求消息),⽐较原⽣。
对于 GetAsync、PostAsync等请求⽅法,使⽤过程类似,下⾯是使⽤⽰例 public async void Request(string url)
{
using (var httpClient = new HttpClient())
{
// HttpClient 中,所有 Get 请求都是异步的
HttpResponseMessage result = await httpClient.GetAsync(url);
// Task<>.Result 可以获取异步结果
result = httpClient.GetAsync(url).Result;
//var result1 = await httpClient.GetByteArrayAsync(url);
//var result1 = await httpClient.GetStreamAsync(url);
//var result1 = await httpClient.GetStringAsync(url);
// ByteArrayContent
FormUrlEncodedContent fromContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("Email","123@qq"),
new KeyValuePair<string, string>("Number","666")
});
// 使⽤ Post ,必须携带继承 HttpContent 的对象
// 就是说,Post 必须要上传数据
result = await httpClient.PostAsync(url, fromContent);
/
/ 如果没有数据要上传,可以使⽤ null
result = await httpClient.PostAsync(url, null);
httpClient.Dispose();
}
三,数据传输
HTTP/HTTPS 请求中,往往随着数据传输,例如表单提交、JSON上传、⽂件上传等,下⾯以代码⽰范。
1. Query
ASP.NET Core API 可以这样写
[HttpPost("aaa")]
public async Task<JsonResult> AAA(int? a, int? b)
{
if (a == null || b == null)
return new JsonResult(new { code = 0, result = "aaaaaaaa" });
return new JsonResult(new { code = 2000, result = a + "|" + b });
}
HttpClient
// URL Query 参数
public void Query(string a, string b)
{
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
};
using (var httpClient = new HttpClient(httpclientHandler))
{
var result = httpClient.PostAsync($"localhost:5001/test?a={a}&b={b}", null).Result;
httpClient.Dispose();
}
}
2. Header
Header 是以键值形式存储的,HttpClient ⽰例
// Header 头
public void Header()
{
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
};
using (var httpClient = new HttpClient(httpclientHandler))
{
httpClient.DefaultRequestHeaders.Add("MyEmail", "123@qq");
var result = httpClient.GetAsync($"localhost:5001/test").Result;
httpClient.Dispose();
}
}
ASP.NET Core API ⽰例
[HttpPost("ddd")]
public async Task<JsonResult> DDD([FromHeader]int? a, [FromHeader]int? b)
{
if (a == null || b == null)
return new JsonResult(new { code = 0, result = "aaaaaaaa" });
return new JsonResult(new { code = 200, result = a + "|" + b });
}
3. 表单
// 表单提交
/
/ application/x-www-form-urlencoded
public void From()
{
var httpclientHandler = new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true,
};
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论