帮助类:
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Net;
namespace RestClienthelp
{
public class RequestHelp
{
/// <summary>
/// get请求
/// </summary>
/// <param name="url">api地址 例http://123.23.23.23/api/asdasda/Test?Code=123123</param>
/// <param name="AuthType">认证方式这里示例两种 一种是cookie(需要在登录或者认证接口返回的响应(respone)的Headers中获取cookie 下面post调用会提到) 一种是Bera</param>
/// <param name="tokenContent">token信息 有则传没有不传</param>
/// <returns></returns>
public (bool, string?) DoGetRequest(string url,string AuthType, string tokenContent)
{
try
{
var client = new RestClient(url);
var request = new RestRequest();//get提交
if (!string.IsNullOrWhiteSpace(AuthType))
{
switch (AuthType)
{
//Bearer认证 如果接口未加密省略此行
case "Bearer": client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenContent); break;
case "Cookie": client.DefaultRequestHeaders.Add("Cookie", tokenContent); break;
}
}
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
//获取到返回信息后 将内容转换成自己想要的结构
//var result = JsonConvert.DeserializeObject<T获取保存体检返回结构>(response.Content);
//因为这里是公用方法不做处理,在上一级的业务类处理,这里只返回
return (true, response.Content);
}
else
{
return (false, $"请求异常:状态码{response.StatusCode};错误信息:{response.ErrorMessage};异常信息:{response.ErrorException}");
}
}
catch (Exception e)
{
return (false, $"请求异常:错误信息:{e.Message};");
}
}
/// <summary>
/// post请求
/// </summary>
/// <param name="Url"></param>
/// <param name="parameter">序列化之后的json 例:{"name":"张三","age":"13"} 可以使用 JsonConvert.SerializeObject(体检详情);序列化实体</param>
/// <param name="ContentType">例如:"application/json"</param>
/// <param name="AuthType">认证方式这里示例两种 一种是cookie(需要在登录或者认证接口返回的响应(respone)的Headers中获取cookie ) 一种是Bera</param>
/// <param name="token">token信息 有则传没有不传</param>
/// <returns></returns>
public (bool, string?) DoPostRequest(string Url, string parameter, string ContentType,string AuthType, string tokenContent)
{
try
{
var client = new RestClient(Url);
var request = new RestRequest("", Method.Post);
request.Timeout = 10000;
//request.AddHeader("Cache-Control", "no-cache");
if (!string.IsNullOrEmpty(AuthType))
{
switch (AuthType)
{
//Bearer认证 如果接口未加密省略此行
case "Bearer": client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); break;
case "Cookie": client.DefaultRequestHeaders.Add("Cookie", token); break;
}
//var authorizationBased64 = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes($"{userName}:{password}"));//basic认证方式 用户名:密码 然后base64加密
//client.DefaultRequestHeaders.Add("Authorization", authorizationBased64);
}
request.AddParameter(ContentType, parameter, ParameterType.RequestBody);
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
//获取到返回信息后 将内容转换成自己想要的结构
//var result = JsonConvert.DeserializeObject<T获取保存体检返回结构>(response.Content);
string CookieValue = "";
if (AuthType == "Cookie"&& Url.EndsWith("login")) {
string[] Cookie = (string[])response.Headers.GetValues("Set-Cookie");
CookieValue = Cookie[0].Split(';')[0];
}
//因为这里是公用方法不做处理,在上一级的业务类处理,这里只返回
return (true, response.Content);
}
else
{
return (false, $"请求异常:状态码{response.StatusCode};错误信息:{response.ErrorMessage};异常信息:{response.ErrorException}");
}
}
catch (Exception e)
{
return (false, $"请求异常:错误信息:{e.Message};");
}
}
}
}
举例:
我们在开发CS架构时通常采用直接链接数据库方式获取数据,这里写下通过RestClient 向第三方接口推送数据、获取数据
准备
1.cs客户端
2.后台api接口(这里采用abp框架)
包控制台安装restsharp
一。登录
登录代码
引用 using RestSharp;
需要给api提供的参数
客户端代码
public int? UserId = null;
public string AccessToken = null;//登录后获取token验证信息
private void button1_Click(object sender, EventArgs e)
{
string UserName = this.textBox1.Text;
string Password = this.textBox2.Text;
string errorMessage = "";
var userId = login(UserName, Password, ref errorMessage);//登录 返回用户ID
if (userId != null)
{
UserId = userId;
//登录成功
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show($"登录失败。错误原因: {errorMessage}");
}
}
public int? login(string userName, string _password, ref string errorMessage)
{
var client = new RestClient("http://localhost:21021/api/TokenAuth/Authenticate");//api地址
var request = new RestRequest(Method.POST);//post提交方式
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(
new
{
userNameOrEmailAddress = userName,//提交的参数
password = _password,
rememberClient = true
});
var response = client.Execute(request);//返回信息
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
string strUserId;
strUserId = result.result.userId;//获取返回信息中的id
this.AccessToken = result.result.accessToken;//获取token验证信息 便于访问其它接口使用
return (int?)int.Parse(strUserId);
}
catch (Exception ex)
{
var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
errorMessage = result.error.details;
return null;
}
}
else
{
var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
if (result == null)
{
errorMessage = "无法连接到服务器。";
}
else
{
errorMessage = result.error.details;
}
return null;
}
}
获取数据
需要给api提交的参数
api返回的结果
客户端代码
private void button2_Click(object sender, EventArgs e)
{
CreateSession(UserId);
}
public void CreateSession(int? userId)
{
string url = "";
var client = new RestClient($"http://localhost:21021/api/services/app/User/Get?Id={userId.ToString()}");
var request = new RestRequest(Method.GET);//get提交
string token = "Bearer " + this.AccessToken;
client.AddDefaultHeader("Authorization", token);//附加token验证信息 登陆时获取
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
var result = JsonConvert.DeserializeObject<AbpWrapUserModel>(response.Content);
var user = result.Result;
Session.CreateSession(
user.Id,
user.UserName,
user.Name,
string.Join(",", user.RoleNames)
);
textBox3.AppendText("id:"+ user.Id+"\r\n"+"name:" + user.Name + "username:" + "\r\n" + user.UserName + "\r\n" );
}
catch (Exception ex)
{
throw;
}
}
else
{
MessageBox.Show($"网络错误。{response.StatusCode.ToString()}");
}
}
class AbpWrapUserModel
{
public UserModel Result { get; set; }
public string TargetUrl { get; set; }
public bool Success { get; set; }
public string Error { get; set; }
public bool UnAuthorizedRequest { get; set; }
public bool __abp { get; set; }
}
class UserModel
{
public string UserName { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string EmailAddress { get; set; }
public string TargetUrl { get; set; }
public bool IsActive { get; set; }
public string FullName { get; set; }
public string LastLoginTime { get; set; }
public string CreationTime { get; set; }
public string[] RoleNames { get; set; }
public int Id { get; set; }
}
public class Session
{
public static int UserId { get; set; }
public static string 创建者用户名 { get; private set; }
public static string 创建者姓名 { get; private set; }
public static string 创建者角色 { get; private set; }
public static string AccessToken { get; set; }
public static void CreateSession(
int userId,
string str用户名,
string str创建者姓名,
string str创建者角色)
{
UserId = userId;
创建者用户名 = str用户名;
创建者姓名 = str创建者姓名;
创建者角色 = str创建者角色;
}
}