WebClient和HttpClient, 以及webapi上傳圖片

MyCoolDog發表於2016-09-23

httppost請求.

applicationkey/x-www-form-urlencoded

請求: Email=321a&Name=kkfew

webapi裡面, 如果用實體, 能接受到. 因為這是一個屬性一個屬性去匹配的原因
application/json

請求:{Email:321a  ,  Name:kkfew}

如果接收引數為dynamic, 則沒有問題.
因為直接把json物件轉化成dynamic物件了

 

 

imageimage

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 + "/" + "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));
            }

        }

相關文章