大家好,又见面了,我是你们的朋友全栈君。
介绍:RestSharp
RestSharp是一个轻量的,不依赖任何第三方的模拟Http的组件或者类库。RestSharp具体以下特性;支持net4.0 ,支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作,支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等。截止当前目前是github最高stars的http类库。
官方文档:https://restsharp.dev/get-help/ github:https://github.com/restsharp/RestSharp
nuget安装:
准备Webapi接口:
代码语言:javascript复制public class UnityController : ApiController
{
private IUserService _userService = null;
public UnityController(IUserService userService)
{
_userService = userService;
}
// GET api/<controller>
public IEnumerable<Student> Get()
{
//return UnityFactoryUtil.GetServer<IUserService>().GetList();
return _userService.GetList();
}
// POST api/<controller>
public string Post([FromBody]string value)
{
return value;
}
[Route("PostTest")]
public string PostTest([FromBody]Student stu)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(stu);
}
}
public class FirstController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
[AllowAnonymous]//不使用验证
public string Get(int id)
{
return "value";
}
[AllowAnonymous]//不使用验证
[Route("GetById")]
public string GetById([FromUri] Student stu)
{
return "value";
}
}
[RoutePrefix("api/File")]
public class FileController : ApiController
{
/// 上传文件
/// </summary>
/// <returns></returns>
[HttpPost]
public string UploadFiles()
{
string result = "";
var path=System.Web.Hosting.HostingEnvironment.MapPath("~/Upload");
HttpFileCollection files = HttpContext.Current.Request.Files;
if (files != null && files.Count > 0)
{
for (int i = 0; i < files.Count; i )
{
HttpPostedFile file = files[i];
string filename = file.FileName;
string FileName = Guid.NewGuid().ToString() Path.GetExtension(filename); ;
string FilePath = path "\" DateTime.Now.ToString("yyyy-MM-dd") "\";
DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists)
{
di.Create();
}
try
{
file.SaveAs(FilePath FileName);
result ="上传成功";
}
catch (Exception ex)
{
result = "上传文件写入失败:" ex.Message;
}
}
}
else
{
result = "上传的文件信息不存在!";
}
return result;
}
/// <summary>
/// 下载文件
/// </summary>
[HttpGet]
public HttpResponseMessage DownloadFile()
{
string fileName = "image.jpg";
string filePath = HttpContext.Current.Server.MapPath("~/Upload/") "image.jpg";
FileStream stream = new FileStream(filePath, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(fileName)
};
response.Headers.Add("Access-Control-Expose-Headers", "FileName");
response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName));
return response;
}
}
使用介绍:
环境:net4.0、RestSharp(105.2.3.0版本)
注意bug:var response=client.Execute<Student>(request); 该方法序列化成实体有问题,可以改成序列化成dynamic(动态类)
代码语言:javascript复制 //Get
{
var client = new RestClient("https://localhost:44370/api/First");
client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin", "admin");
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.Timeout = 10000;
request.AddHeader("Cache-Control", "no-cache");
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// add parameters for all properties on an object
//request.AddJsonObject(@object);
//直接传输一个实体
//request.AddJsonBody("实体");
//request.AddObject(object, "PersonId", "Name", ...);
request.AddHeader("header", "value");
//add files to upload (works with compatible verbs)
//request.AddFile("file", path);
var response = client.Execute(request);
var content = response.Content;
}
//POST(单个参数与)
{
var client = new RestClient("https://localhost:44370/api/Unity");
var request = new RestRequest(Method.POST);
request.AddParameter("", "value");
var response = client.Execute(request);
var content = response.Content;
}
//POST(实体参数)
{
var client = new RestClient("https://localhost:44370/api/Unity/PostTest");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
Student stu = new Student
{
AGE = 26,
ID = 1,
NAME = "czk",
PWD = 123456
};
request.AddJsonBody(stu);
//var response = client.Execute<Student>(request);//报错、
var response = client.Execute<dynamic>(request);
var retStu = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(response.Data);
}
//上传文件
{
var client = new RestClient("https://localhost:44370/api/File/UploadFiles");
var request = new RestRequest(Method.POST);
var imagePath = AppDomain.CurrentDomain.BaseDirectory @"Fileimage.jpg";
request.AddFile("image", imagePath);
var response = client.Execute(request);
var content = response.Content;
}
//下载文件
{
var client = new RestClient("https://localhost:44370/api/File/DownloadFile");
var request = new RestRequest(Method.GET);
string tempFile = Path.GetTempFileName();
var writer = File.OpenWrite(tempFile);
request.ResponseWriter = responseStream =>
{
using (responseStream)
{
responseStream.CopyTo(writer);
}
};
byte[] bytes = client.DownloadData(request);
}
扩展:
c# EasyHttp (http请求库):https://blog.csdn.net/czjnoe/article/details/106483861
demo:https://github.com/czjnoe/GitHubDemo/tree/master/RestSharpDemo
github下载慢参考:https://blog.csdn.net/czjnoe/article/details/106321174
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/197722.html原文链接:https://javaforall.cn