WebClient和HttpClient, 以及webapi上传图片

时间:2022-06-01 12:52:52

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 = ""; //下面代码让异步变成同步, 因为要返回上传完图片之后新的图片绝对路径 IEnumerable parts = 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 + "http://www.mamicode.com/" + "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上传图片