EasyHttp http请求类库,支持net4.0++
github:https://github.com/EasyHttp/EasyHttp
环境:net4.0 、EasyHttp(1.7版本)
准备工作:准备webapi调用接口
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;
}
}
http请求:
//GET(无参)
{
var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
//http.Request.ContentType = "application/json";
http.Request.SetBasicAuthentication("admin", "admin");
var response = http.Get("https://localhost:44370/api/First");
string responseValue = response.RawText;
//var dyncValue=response.DynamicBody;
}
//GET(单个传参)
{
var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
//http.Request.ContentType = "application/json";
http.Request.SetBasicAuthentication("admin", "admin");
var response = http.Get("https://localhost:44370/api/First?id=5");
string responseValue = response.RawText;
//T obj=response.StaticBody<T>();
//var dyncValue=response.DynamicBody;
}
//GET(实体传参)
{
var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
//http.Request.ContentType = "application/json";
http.Request.SetBasicAuthentication("admin", "admin");
Student stu = new Student
{
AGE = 25,
ID = 1,
NAME = "czj",
PWD = 123456
};
var response = http.Get("https://localhost:44370/api/First/GetById", stu);
string responseValue = response.RawText;
//T obj=response.StaticBody<T>();
//var dyncValue=response.DynamicBody;
}
//POST(单个参数)
{
var http = new HttpClient();
http.Request.SetBasicAuthentication("admin", "admin");
//http.Request.Uri = "https://localhost:44370/api/Unity";
Dictionary<string, object> dic = new Dictionary<string, object>();
dic[""] = "value";
var response = http.Post("https://localhost:44370/api/Unity", dic, EasyHttp.Http.HttpContentTypes.ApplicationXWwwFormUrlEncoded);
string responseValue = response.RawText;
}
//POST(参数为实体/dynamic)
{
var http = new HttpClient();
http.Request.SetBasicAuthentication("admin", "admin");
Student stu = new Student
{
AGE = 25,
ID = 1,
NAME = "czj",
PWD = 123456
};
var response = http.Post("https://localhost:44370/api/Unity/PostTest", stu, EasyHttp.Http.HttpContentTypes.ApplicationJson);
var responseValue = response.DynamicBody;
Student retStu = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(responseValue);
}
//上传文件
{
string uri = "https://localhost:44370/api/File/UploadFiles";
var http = new HttpClient();
var imagePath = AppDomain.CurrentDomain.BaseDirectory + @"File\image.jpg";
List<FileData> list = new List<FileData>();
FileData file = new FileData
{
FieldName = "image.jpg",
Filename = imagePath
};
list.Add(file);
var response = http.Post(uri, null, list);
var value = response.RawText;
}
//下载文件
{
string uri = "https://localhost:44370/api/File/DownloadFile";
var http = new HttpClient();
var imagePath = AppDomain.CurrentDomain.BaseDirectory + $@"File\{Guid.NewGuid().ToString()}.jpg";
var response = http.GetAsFile(uri, imagePath);
}
扩展:c# RestSharp(http请求):https://blog.csdn.net/czjnoe/article/details/106482422
demo:https://github.com/czjnoe/GitHubDemo/tree/master/EasyHttpDemo
github下载慢参考:https://blog.csdn.net/czjnoe/article/details/106321174