C#Winform中通过RestSharp调用Java的Restful接口的常规操作
- 背景
- Restful API接口发布
- 在C#中使用RestSharp调用Restful API
- 使用RestSharp调用Get接口
- 在C#中使用RestSharp调用Post接口
- 在C#中使用RestSharp实现文件上传
- 在C#中使用RestSharp实现文件下载
背景
由于Restful协议格式的API接口越来越流行,作为异构系统的便捷集成方式,在不同编程语言中如何方便的发布和调用Restful接口成为了各为码神必备技能之一。
Restful API接口发布
Restful API接口发布我们采用了最流程的互联网技术spring boot + spring mvc + mybatis-plus + swagger。由于本文主要讲解RestSharp的使用,因此这部分不是本文的重点,看一下swagger中看到的接口说明如下图:
在C#中使用RestSharp调用Restful API
使用RestSharp调用Get接口
接口如下图:
接口调用示例代码如下:
Mesnac.Basic.Cloud.CloudProjectInfo[] projectInfoList = null;
#region 云端接口调用
try
{
string url = Mesnac.Basic.AppConfigHelper.GetAppSettingValue("CloudAPIUrl", "http://121.36.91.30:8088");
url += "/api/project/getProjectList";
RestSharp.RestClient client = new RestSharp.RestClient();
client.BaseUrl = url;
client.Authenticator = new RestSharp.HttpBasicAuthenticator("username", "password");
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.Method = RestSharp.Method.GET;
if (!String.IsNullOrEmpty(projectName))
{
request.AddParameter("name", projectName);
}
request.AddParameter("username", account);
request.AddParameter("password", password);
RestSharp.IRestResponse response = client.Execute(request);
if (response.ErrorException != null)
{
//失败
ICSharpCode.Core.LoggingService<FrmCloudBrower>.Warn(String.Format("调用云端获取工程列表接口[{0}]失败:{1}", url, response.ErrorMessage));
MessageBox.Show(response.ErrorMessage, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string jsonResult = response.Content;
if (String.IsNullOrEmpty(jsonResult))
{
string msg11 = StringParser.Parse(ResourceService.GetString("Wongoing_Dialog_FrmCloudRegister_msg11")); //调用云端接口失败,返回内容为空!
MessageBox.Show(msg11, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Mesnac.Basic.Cloud.ResponseResult responseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Mesnac.Basic.Cloud.ResponseResult>(jsonResult);
if (!responseResult.Status)
{
//失败
ICSharpCode.Core.LoggingService<FrmCloudBrower>.Error(String.Format("msg = {0}, data = {1}", responseResult.Msg, responseResult.Data));
MessageBox.Show(responseResult.Msg, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
//成功!
projectInfoList = Newtonsoft.Json.JsonConvert.DeserializeObject<Mesnac.Basic.Cloud.CloudProjectInfo[]>(responseResult.Data.ToString());
this.gridControl1.DataSource = projectInfoList; //把数据绑定到表格中
}
}
catch (Exception ex)
{
ICSharpCode.Core.LoggingService<FrmCloudBrower>.Error(ex.Message, ex);
MessageBox.Show(ex.Message, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
#endregion
在C#中使用RestSharp调用Post接口
接口如下图:
接口调用示例代码如下:
#region 调用云端接口进行注册
try
{
string url = Mesnac.Basic.AppConfigHelper.GetAppSettingValue("CloudAPIUrl", "http://121.36.91.30:8088");
url += "/api/user/userRegister";
RestSharp.RestClient client = new RestSharp.RestClient();
client.BaseUrl = url;
client.Authenticator = new RestSharp.HttpBasicAuthenticator("username", "password");
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.Method = RestSharp.Method.POST;
request.AddParameter("uuid", Wongoing.HardwareTools.GetUuid());
if (!String.IsNullOrEmpty(this.txtName.Text.Trim()))
{
request.AddParameter("name", this.txtName.Text.Trim());
}
request.AddParameter("sex", sex);
request.AddParameter("account", this.txtAccount.Text.Trim());
request.AddParameter("phone", this.txtPhone.Text.Trim());
request.AddParameter("email", this.txtEmail.Text.Trim());
request.AddParameter("password", this.txtPassword.Text.Trim());
request.AddParameter("remark", this.txtMachineCode.Text.Trim());
RestSharp.IRestResponse response = client.Execute(request);
if (response.ErrorException != null)
{
//失败
ICSharpCode.Core.LoggingService<FrmCloudRegister>.Warn(String.Format("调用云端注册接口[{0}]失败:{1}", url, response.ErrorMessage));
MessageBox.Show(response.ErrorMessage, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string jsonResult = response.Content;
if (String.IsNullOrEmpty(jsonResult))
{
string msg11 = StringParser.Parse(ResourceService.GetString("Wongoing_Dialog_FrmCloudRegister_msg11")); //调用云端接口失败,返回内容为空!
MessageBox.Show(msg11, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Mesnac.Basic.Cloud.ResponseResult responseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Mesnac.Basic.Cloud.ResponseResult>(jsonResult);
if (!responseResult.Status)
{
//失败
ICSharpCode.Core.LoggingService<FrmCloudRegister>.Error(String.Format("msg = {0}, data = {1}", responseResult.Msg, responseResult.Data));
MessageBox.Show(responseResult.Msg, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
//成功!
Wongoing.RegisteredTools.UserAccount = Mesnac.Basic.UserInfo.Instance.CloudUser.Account; //把用户账户保存在注册表中
Wongoing.RegisteredTools.UserPassword = Mesnac.Basic.UserInfo.Instance.CloudUser.Password; //把用户密码保存在注册表中
string msg9 = StringParser.Parse(ResourceService.GetString("Wongoing_Dialog_FrmCloudRegister_msg9")); //注册成功,请进行登录以使用云端服务!
MessageBox.Show(msg9, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
catch(Exception ex)
{
ICSharpCode.Core.LoggingService<FrmCloudRegister>.Error(ex.Message, ex);
MessageBox.Show(ex.Message, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
#endregion
在C#中使用RestSharp实现文件上传
接口如下图:
接口调用示例代码如下:
#region 把压缩好的文件上传云端
string url = Mesnac.Basic.AppConfigHelper.GetAppSettingValue("CloudAPIUrl", "http://121.36.91.30:8090");
url += "/api/project/doAddSingleProjectWithFile";
//string paramData = "active=add&projectName=Project2&projectDescription=Project2&creatorAccount=zhenglibing&projectNumber=Project2";
RestSharp.RestClient client = new RestSharp.RestClient();
client.BaseUrl = url;
client.Authenticator = new RestSharp.HttpBasicAuthenticator("username", "password");
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.Method = RestSharp.Method.POST;
request.AddFile("projectFileAddOrEdit", targetZipProjectFile);
request.AddParameter("active", "add");
request.AddParameter("projectName", fileName);
request.AddParameter("projectDescription", fileName);
request.AddParameter("creatorAccount", Wongoing.RegisteredTools.UserAccount);
request.AddParameter("projectNumber", fileName);
request.AddParameter("password", Wongoing.RegisteredTools.UserPassword);
RestSharp.IRestResponse response = client.Execute(request);
if (response.ErrorException != null)
{
ICSharpCode.Core.LoggingService<FrmCloudLogin>.Warn(String.Format("调用云端上传接口[{0}]失败:{1}", url, response.ErrorMessage));
MessageBox.Show(response.ErrorMessage, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string jsonResult = response.Content;
if (String.IsNullOrEmpty(jsonResult))
{
string msg11 = StringParser.Parse(ResourceService.GetString("Wongoing_Dialog_FrmCloudRegister_msg11")); //调用云端接口失败,返回内容为空!
MessageBox.Show(msg11, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Mesnac.Basic.Cloud.ResponseResult responseResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Mesnac.Basic.Cloud.ResponseResult>(jsonResult);
if (!responseResult.Status)
{
//失败
ICSharpCode.Core.LoggingService<FrmCloudRegister>.Error(String.Format("msg = {0}, data = {1}", responseResult.Msg, responseResult.Data));
MessageBox.Show(responseResult.Msg, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
string msgSuccess = "上传云端成功!";
MessageBox.Show(msgSuccess, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
在C#中使用RestSharp实现文件下载
接口如下图:
接口调用示例代码如下:
#region 调用云端下载接口
try
{
string url = Mesnac.Basic.AppConfigHelper.GetAppSettingValue("CloudAPIUrl", "http://121.36.91.30:8088");
url += "/api/project/projectDownload";
RestSharp.RestClient client = new RestSharp.RestClient();
client.BaseUrl = url;
client.Authenticator = new RestSharp.HttpBasicAuthenticator("username", "password");
RestSharp.RestRequest request = new RestSharp.RestRequest();
request.Method = RestSharp.Method.GET;
request.AddParameter("projectId", projectId);
request.AddParameter("username", Wongoing.RegisteredTools.UserAccount);
request.AddParameter("password", Wongoing.RegisteredTools.UserPassword);
byte[] content = client.DownloadData(request);
if (content == null || content.Length == 0)
{
string msg11 = StringParser.Parse(ResourceService.GetString("Wongoing_Dialog_FrmCloudRegister_msg11")); //调用云端接口失败,返回内容为空!
MessageBox.Show(msg11, Mesnac.Basic.LanguageHelper.Caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
fs.Write(content, 0, content.Length);
fs.Close();
}
return true;
}
catch (Exception ex)
{
ICSharpCode.Core.LoggingService<FrmCloudBrower>.Error(ex.Message, ex);
MessageBox.Show(ex.Message, Mesnac.Basic.LanguageHelper.ErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
#endregion