WebClient和HttpClient, 以及webapi上传图片
Posted 风继续吹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebClient和HttpClient, 以及webapi上传图片相关的知识,希望对你有一定的参考价值。
httppost请求.
applicationkey/x-www-form-urlencoded 请求: Email=321a&Name=kkfew webapi里面, 如果用实体, 能接受到. 因为这是一个属性一个属性去匹配的原因 | application/json 请求:{Email:321a , Name:kkfew} 如果接收参数为dynamic, 则没有问题. 因为直接把json对象转化成dynamic对象了 |
using (WebClient webclient = new WebClient()) { string apiurl = "http://192.168.1.225:9090/api/v3productsapi/GetStatisticInfo"; webclient.Encoding = UTF8Encoding.UTF8; string auth_key = string.Format("{0}:{1}:{2}", ts.TotalSeconds, randomStr, token); webclient.Headers.Add("Custom-Auth-Key", auth_key); Console.Write(webclient.DownloadString(apiurl)); } using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://192.168.1.225:9090/"); client.DefaultRequestHeaders.Add("aa", "11"); var result = client.GetStringAsync("/api/v3productsapi/GetStatisticInfo").Result; Console.WriteLine(result); }
post
System.Web.Script.Serialization.javascriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer(); using (var client = new HttpClient())//httpclient的post方式, 需要被实体接收.. { string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform2"; //3个枚举, stringContent,ByteArrayContent,和FormUrlContent, 一般的post用StringContent就可以了 using (var content = new StringContent( "Email=321a&Name=kkfew", Encoding.UTF8, "application/x-www-form-urlencoded")) { content.Headers.Add("aa", "11"); //默认会使用 var result = client.PostAsync(apiurl, content).Result; Console.WriteLine(result); } } using (var client = new HttpClient()) { string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform"; using (var content = new StringContent(json.Serialize(new { Email = "1", Name = "2" }))) { content.Headers.Add("aa", "11"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = client.PostAsync(apiurl, content).Result; Console.WriteLine(result); } } using (WebClient webclient = new WebClient()) { string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform2"; webclient.Encoding = UTF8Encoding.UTF8; webclient.Headers.Add("Custom-Auth-Key", "11"); webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//x-www-form-urlencoded //如果webapi的接收参数对象是dynamic, 则请求的头是json, 如果是用实体接收, 那么则是上面这个 var re = webclient.UploadData(apiurl, System.Text.Encoding.UTF8.GetBytes("Email=321a&Name=kkfew")); Console.Write(System.Text.Encoding.UTF8.GetString(re)); } using (WebClient webclient = new WebClient()) { string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/posttestform"; webclient.Encoding = UTF8Encoding.UTF8; webclient.Headers.Add("Custom-Auth-Key", "11"); webclient.Headers.Add("Content-Type", "application/json");//x-www-form-urlencoded //如果webapi的接收参数对象是dynamic, 则请求的头是json, 如果是用实体接收, 那么则是上面这个 var re = webclient.UploadData(apiurl, System.Text.Encoding.UTF8.GetBytes(json.Serialize(new { email = "123456@qq.com", password = "111111" }))); Console.Write(System.Text.Encoding.UTF8.GetString(re)); }
上传图片
using (WebClient webclient = new WebClient()) { string apiurl = "http://192.168.1.225:9090/api/V3ImageUploadApi/post"; webclient.Encoding = UTF8Encoding.UTF8; string auth_key = string.Format("aa", "111"); webclient.Headers.Add("Custom-Auth-Key", auth_key); byte[] b = webclient.UploadFile(apiurl, @"c:\\2.jpg"); Console.Write(System.Text.Encoding.UTF8.GetString(b)); } using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { client.BaseAddress = new Uri("http://192.168.1.225:9090/"); var fileContent = new ByteArrayContent(File.ReadAllBytes(@"c:\\1.jpg")); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "1.jpg" }; content.Add(fileContent); content.Headers.Add("aa", "ssssss"); var result = client.PostAsync("/api/V3ImageUploadApi/post", content).Result; Console.WriteLine(result.Content.ReadAsStringAsync().Result); } }
[HttpPost] public HttpResponseMessage Post() { try { if (!IsValidateTokenPost) { return TokenException(); } if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var apiResult = new ApiResult(); string root = HostingEnvironment.MapPath("~/content/images/uploaded/fromwechart"); if (!System.IO.Directory.Exists(root)) System.IO.Directory.CreateDirectory(root); var provider = new MultipartFormDataStreamProvider(root); string OssFilename = ""; //下面代码让异步变成同步, 因为要返回上传完图片之后新的图片绝对路径 IEnumerableparts = null; Task.Factory .StartNew(() => { parts = Request.Content.ReadAsMultipartAsync(provider).Result.Contents; foreach (MultipartFileData file in provider.FileData) { //Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Trace.WriteLine("Server file path: " + file.LocalFileName); var fileName = file.Headers.ContentDisposition.FileName; OssFilename = System.Guid.NewGuid() + "." + fileName.Split(\'.\')[1]; using (FileStream fs = new FileStream(file.LocalFileName, FileMode.Open)) { PutImageFileToOss(fs, "image/" + fileName.Split(\'.\')[1], OssFilename); } if (File.Exists(file.LocalFileName))//上传完删除 File.Delete(file.LocalFileName); } }, CancellationToken.None, TaskCreationOptions.LongRunning, // guarantees separate thread TaskScheduler.Default) .Wait(); string picUrl = "http://" + OssService.OssConfig.Domain + "/" + "content/sitefiles/" + _StoreContext.CurrentStore.SiteId + "/images/" + OssFilename; return Json(new ApiResult { StatusCode = StatusCode.成功, Info = new { filename = picUrl } }); } catch (Exception ex) { return Json(ApiResult.InnerException(ex)); } }
以上是关于WebClient和HttpClient, 以及webapi上传图片的主要内容,如果未能解决你的问题,请参考以下文章
WebClient、HttpWebRequest 和 HttpClient 的最大并发请求数
如何在 .NET 6 中用 HttpClient 替换过时的 WebClient
WebClient, HttpClient, HttpWebRequest ,RestSharp之间的区别与抉择